After searching and trying several options over the last week, I can't seem to find what I am looking for; maybe someone here can help. While reading through this, please keep in mind that I am attempting to utilize MVVM as strictly as possible, though I am relatively new to WPF. As a side note, I am using Mahapps.Metro to style my window and controls, found here.
I have an XML file that my application uses for configuration (I cannot use the app.config file because the application cannot install on the users' systems). The application will look for this file at start-up and if it does not find the file, it will create it. Below is a snippet of the XML:
<?xml version="1.0" encoding="utf-8"?>
<prefRoot>
<tabReport>
<cbCritical>True</cbCritical>
</tabReport>
</prefRoot>
I reference the XML file in my Window.Resources:
<Controls:MetroWindow.Resources>
<XmlDataProvider x:Key="XmlConfig"
Source="%appdata%\Vulnerator\Vulnerator_Config.xml"
XPath="prefRoot"
IsAsynchronous="False"
IsInitialLoadEnabled="True"/>
</Controls:MetroWindow.Resources>
And utilize this as the DataContext for my MainWindow:
<Controls:MetroWindow DataContext="{DynamicResource XmlConfig}">
Next, I set up a "string-to-bool" converter:
class StringToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
bool? isChecked = (bool?)value;
return isChecked;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
string isChecked = value.ToString();
return isChecked;
}
return string.Empty;
}
}
Finally, I bind IsChecked to the appropriate XPath:
<Checkbox x:Name="cbCritical"
Content="Critical"
IsChecked="{Binding XPath=//tabReport/cbCritical,
Converter={StaticResource StringToBool}}" />
After all of this, the applciation loads, but IsChecked is set to false... Any and all ideas would be helpful here; thanks in advance!
I figured out the issue... XAML does not handle % in a file path as expected. To correct, I removed the following from my XAML XmlDataProvider declaration:
Source="%appdata%\Vulnerator\Vulnerator_Config.xml"
XPath="prefRoot"
I then set the Source and XPath properties in my code-behind (.xaml.cs):
public MainWindow()
{
InitializeComponent();
Uri xmlPath = new Uri (Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Vulnerator\Vulnerator_Config.xml");
(this.Resources["XmlConfig"] as XmlDataProvider).Source = xmlPath;
(this.Resources["XmlConfig"] as XmlDataProvider).XPath = "prefRoot";
}
Now, when the application loads, the checkbox is set to the inner value of the XML node specified. Also, I set the Binding Mode=TwoWay to OneTime; two way binding to an XmlDataProvider doesn't occur as expected. To get around this, I am going to bind a command to the Checkbox to update a Dictionary<string, string> (created at startup in my view-model constructer) with the new IsChecked value. I will use the Dictionary to control what the application does based off of user input, and write the new Dictionary user values to the XML file once the application is closed.
Related
I'm sitting in front of the following unit test without getting it to work properly
[TestMethod]
public void EvenIndexesZeroShouldHaveWhiteBackground()
{
var converterBinding = new Binding("BackgroundConverter");
converterBinding.Converter = new BackgroundConverter();
var lvi0 = new ListViewItem() { Background = Brushes.Gray };
var lv = new ListView();
lvi0.SetBinding(ListViewItem.BackgroundProperty, converterBinding);
lv.Items.Add(lvi0);
Assert.AreEqual(Brushes.White, converterBinding.Converter.Convert(lvi0, null, null, CultureInfo.InvariantCulture));
}
I was able to get another converter tested by directly calling the Convert(...) method, but it received a simple data type.
I have the feeling that I somehow need to trigger the converter when adding lvi0to the ListView(or manually afterwards) but I don't know how to do it.
Can anyone point me in the right direction?
I'm new to WPF and haven't fully gotten my head around the Bindings and Dependency Properties yet :(
[UPDATE]
The current problem is that the Convertmethod isn't called. It's not the content of the converter or the result it is giving back.
[UPDATE 2]
#Tatranskymedved comment pointed me into the right direction and calling the converter directly (as proposed by #PeterDuniho) now works. I have updated the code snippet above accordingly.
[UPDATE 3]
Here is the Converter. I HAVE to pass in a ListViewItem since this is what the it is working on. Changing it is currently not an option.
public class BackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ListViewItem item = value as ListViewItem;
if (item == null) return Brushes.White;
ListView listView = ItemsControl.ItemsControlFromItemContainer(item) as ListView;
// Get the index of a ListViewItem
if (listView == null)
return Brushes.White;
int index = listView.ItemContainerGenerator.IndexFromContainer(item);
if (index % 2 == 0)
{
return Brushes.WhiteSmoke;
}
return Brushes.White;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
The basic idea is: In WPF You are using some Window/UserControl, where are layouts and controls. If any of the controls should have binded its property to the ViewModel, property of the Control must be defined as DependencyProperty. If You are just using some already defined controls, You do not need to known them.
When You are creating own UserControl, it has to have a DependencyProperty, so You can bind one end to it.
Now You have to realize, what do You want to test. Is it the binding? Or the converter itself?
For the binding test, You can refer to this: Unit test WPF Bindings
Or: http://www.wpf-tutorial.com/data-binding/debugging/
However, talking about unit tests, You should test the Converter directly instead of putting them to the complicated chain objects like Binding. That is the basic motivation if the test won't work, You can say "the problem is with the Converter", not with the binding or the object You will bind to.
Only thing You need to check if the type of value You setting is the correct one. For WPF Control's BackgroundProperty it should be System.Windows.Media.Brush as on MSDN.
I need to create a horizontal list view for a Windows Store application with full screen image items, something like the Gallery control for Android. To do this, I've used a GridView and changed the ItemsPanel template to be a VirtualizingStackPanel with horizontal orientation. The problem is that I cannot make the Image items to be full screen. What I've tried is to make the GridView.ItemContainerStyle to bind to the GridView's width, like this:
Binding widthBinding = new Binding() { Source=iconsHolder, Path = new PropertyPath("Width"), Converter = new TestItemWidthConverter()};
Style itemStyle = new Style();
itemStyle.TargetType = typeof(GridViewItem);
itemStyle.Setters.Add(new Setter(GridViewItem.WidthProperty, widthBinding));// 800));
iconsHolder.ItemContainerStyle = itemStyle;
When I replace the widthBinding with 800, for example, the icons have the specified width, but when I use the binding, no items are visible, so the Style do its job, but the Binding has a problem. In order to debug this, I've created a fake converter, so I can see if the binding works, but the Convert(..) method isn't called at all.
My GridView is created like this:
GridView iconsHolder = new GridView();
iconsHolder.ItemsPanel = App.Current.Resources["HorizontalVSPTemplate"] as ItemsPanelTemplate;
iconsHolder.ItemTemplate = App.Current.Resources["MyDataTemplate"] as DataTemplate;
iconsHolder.Width = Window.Current.Bounds.Width;
iconsHolder.Height = Window.Current.Bounds.Height;
and my resources are defined like:
<ItemsPanelTemplate x:Key="HorizontalVSPTemplate">
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
<DataTemplate x:Key="MyDataTemplate">
<Image Source="some irrelevant url here"/>
</DataTemplate>
My converter looks like this:
public sealed class TestItemWidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Debug.WriteLine(" binding width=" + value);
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{ return value; }
}
I don't know how to achieve this (I've also tried using RelativeBinding or make Icons to be horizontally stretched, without success) or what I'm doing wrong, so please help!
Thank you for your time!
I've figure it out that I was on the wrong path, the right way to do it was to use FlipView, just as simple as
FlipView iconsHolder = new FlipView();
iconsHolder.ItemsSource = myItems;
iconsHolder.ItemTemplate = App.Current.Resources["MyDataTemplate"] as DataTemplate;
Now my icons are full screen by default and the scroll effect is paged. Some useful details about this control can be found here: Quickstart: Adding FlipView controls .
I have a user control containing a text box and a label, the label display the length of the input text (with some formatting). I want to change the background color of the text box if the text is longer than 160 characters.
I was thinking of achieving this with bindings, but since the length of the text contain tag to be replaced I'm not willing to have 2 different binding making the same computing.
I don't succeed in changing
I can think of three way to achieves this :
1) create a hidden label with all tags replaced in his text, then have two simple converter to bind display the message length and change the background color. 3 converter for such a basic task seems too much to me.
2) Use the text_changed event to do the work. This work but it seems to me its not the way to do things in WPF.
3) Use a multibinding and pass my form as a source, this should work but looks too much 'god object' approach to me.
What do you think of that ? Am I missing a cleaner/simpler solution ?
Any suggestion is welcome, Thanks in advance.
You can create another property TBBackColor, and bind your textbox BackgroundColor to it.
Something like:
Public System.Windows.Media.Brush TBBackColor
{
get
{
return (TBText.Length>160)? new SolidColorBrush(Color.Red): new SolidColorBrush(Color.White);
}
}
And remember in your TBText property (if that is the one bind to your TextBox: Text) you need to raise propertychanged event for TBBackColor too.
Using a converter is a good idea in this case, but you won't need multiple converters. Instead, we define one converter with multiple parameters:
public class TextBoxValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || string.IsNullOrEmpty(parameter as string))
throw new ArgumentException("Invalid arguments specified for the converter.");
switch (parameter.ToString())
{
case "labelText":
return string.Format("There are {0} characters in the TextBox.", ((string)value).Count());
case "backgroundColor":
return ((string)value).Count() > 20 ? Brushes.SkyBlue : Brushes.White;
default:
throw new ArgumentException("Invalid paramater specified for the converter.");
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And then in your XAML you use it like this:
<TextBox Name="textBox" Background="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource converter}, ConverterParameter=backgroundColor}"/>
<Label Content="{Binding ElementName=textBox, Path=Text, Converter={StaticResource converter}, ConverterParameter=labelText}"/>
How do I use an IValueConverter to convert nulls into booleans?
I'm using wpf to try to display a bunch of boolean values (in checkboxes). When a new record is created, these values are null, and appear as 'indeterminate' in the checkboxes. I want the nulls to appear and save as 'false' values.
I tried to create a NullToBoolean converter that takes null values from the database and displays them as false, and then saves them as false when the user hits save. (Essentially, I'm trying to avoid the user having to click twice in the checkboxes (once to make it true, then again to make it false). This seems to work on import - ie null values are shown as false - but unless I do the two-click dance the value doesn't change in the database when I save.
My Converter:
[ValueConversion(typeof(bool), typeof(bool))]
public class NullBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
return value;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
return value;
}
return null;
}
}
One of the checkboxes I'm trying to have the Converter work with:
<CheckBox Grid.Column="1" Grid.Row="0" Padding="5" Margin="5" VerticalAlignment="Center" Name="chkVarianceDescriptionProvided" IsThreeState="False">
<CheckBox.IsChecked>
<Binding Path="VarianceDescriptionProvided" Mode="TwoWay">
<Binding.Converter>
<utils:NullBooleanConverter />
</Binding.Converter>
</Binding>
</CheckBox.IsChecked>
</CheckBox>
I don't know if the problem is because my code is wrong, or if it's a case of the Converter thinking that nothing has changed, therefore it doesn't need to ConvertBack. I have tried all the Modes and switched code in Convert with ConvertBack, but nothing seems to work.
Can someone point out what I need to do to fix this?
Hmm, why using a converter, if you can have it out of the box?
<CheckBox IsChecked="{Binding VarianceDescriptionProvided, TargetNullValue=False}" />
For more information, pls have a look here.
The real problem is the fact you are not initializing your data objects in the first place. Don't "fix", do it right to begin with; builders are good (for example). You also should be making ViewModels/DataModels rather than working with your Models (database, etc) directly.
public class MyObjectBuilder
{
Checked _checked;
public MyObjectBuilder()
{
Reset()
}
private void Reset()
{
_checked = new Checked(true); //etc
}
public MyObjectBuilder WithChecked(bool checked)
{
_checked = new Checked(checked);
}
public MyObject Build()
{
var built = new MyObject(){Checked = _checked;}
Reset();
return built;
}
}
then always initialise with the builder
myObjects.Add(new MyObjectBuilder().Build());
or
myObjects.Add(_injectedBuilder.Build()); // Initialises Checked to default
myObjects.Add(_injectedBuilder.WithChecked(true).Build()); //True
While this doesn't fix your asked problem, it will fix your underlying problem in a way you can Unit Test. i.e. you can test to ensure the values added into your object list are always initialized.
Simply correct your data before you perform data binding. That is the only option. The converter will only work make the check box show as 'unchecked' and update your data only when you interact with the control. For example:
foreach (var item in items)
{
if (item.VarianceDescriptionProvided == null)
item.VarianceDescriptionProvided = false;
}
Scenario: A ListView is DataBound to an ObservableCollection<CustomClass> and is displaying it's items through a custom ItemTemplate. The CustomClass just contains three string properties and one boolean property and already has INotifyPropertyChanged implemented on every of it's four properties. The custom ItemTemplate of the ListView has One-Way bindings on the three string properties and a Two-Way binding on the boolean property, displaying it as a CheckBox.
Problem: I'm looking for the most elegant (in terms of WPF) way to display the count of all checked items in that ListView using a TextBlock - or in other words, all items that have their boolean property set to true in that collection. I want that TextBlock to immediately update the displayed count if one of the ListView items gets checked/unchecked. I know that there are (rather) ugly ways to achieve this with code behind and eventhandling, but I'd like to know if there's a clever way to do this maybe completely in XAML with arcane DataBinding syntax.
Edit: Just as an example/clarification: The ListView displays 100 items, 90 items have their boolean property set to true, so the TextBlock will display '90'. If the user unchecks one more item through it's CheckBox and therefore sets it's property to false through the Two-Way binding, the TextBlock should update to '89'.
Personally I would probably perform this in my ViewModel. Subscribe to the property changed on the items in the ObservableCollection, and then signal the Count property changed on the ViewModel whenever the boolean property changes. In your view simply bind to the Count property.
You could use a Converter to build up a string with the count of the checked items
public sealed class CountToStringConverter : System.Windows.Data.IValueConverter {
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
ObservableCollection<CustomClass> items = value as ObservableCollection<CustomClass>;
int count = 0;
foreach (var item in items) {
if (item.IsChecked) {
count++;
}
}
return count + " Items";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
#endregion
}
Bind the Text-Property of the TextBox to the Collection.
<TextBox Text={Binding Items, Converter={StaticResource countToStringConverter}}/>
UPDATE:
This Binding works only if the Property Items fires the PropertyChanged-Event, if the Collection is changed.
If it were a simple ASP.NET form, I'd look at using JQuery to count the selected items in the ListBox. That may still be a viable option in WPF:
var count = 0;
$('#multiItemListBox :selected').each(count++);
Plug this code into a JS event handler for the OnChange event of the ListBox. You'll have to know what the ListBox would actually be called in the HTML the client gets, and I'm not sure how WPF mashes them up or how to stick the correct reference into server-side XAML.
Thanks for all the answers I've got, these were all applicable solutions but unfortunately not really what I've tried to achieve. So this is how I've solved the problem now:
I've implemented a DependencyProperty on the Window containing the TextBlock:
public static readonly DependencyProperty ActiveItemCountProperty =
DependencyProperty.Register("ActiveItemCount", typeof(int), typeof(CustomControl), new UIPropertyMetadata(0));
On the DataTemplate for the ListView items the CheckBox registered an EventHandler for the Click-Event:
<CheckBox IsChecked="{Binding Active, Mode=TwoWay}" Click="CheckBox_Click" />
The event handler in code behind looks something like this:
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
ObservableCollection<CustomClass> sourceCol = listView.DataContext as ObservableCollection<CustomClass>;
if (sourceCol != null)
ActiveItemCount = sourceCol.Count(x => x.Active);
}
And obviously, the TextBlock is just data bound to this DependencyProperty:
<TextBlock Text="{Binding Path=ActiveItemCount, ElementName=ControlRoot}" />
With ControlRoot being the name of the Window.