I want to display multiple rectangles with some properties, which I store in an Array of Arrays. The XAML for displaying looks like this:
<UserControl x:Class="Project.Views.SomeView">
<UserControl.Resources>
<DataTemplate x:Key="ObjectRowTemplate">
<Rectangle Fill="{Binding Path=color, UpdateSourceTrigger=PropertyChanged}" Height="15" Width="30" StrokeThickness="1px" Stroke="Blue" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<catel:EventToCommand DisableAssociatedObjectOnCannotExecute="False">
<catel:EventToCommand.Command>
<Binding RelativeSource="{RelativeSource AncestorType={x:Type Canvas}}" Path="DataContext.ObjectClickedCommand" />
</catel:EventToCommand.Command>
<catel:EventToCommand.CommandParameter>
<Binding Path="." />
</catel:EventToCommand.CommandParameter>
</catel:EventToCommand>
</i:EventTrigger>
</i:Interaction.Triggers>
</Rectangle>
</DataTemplate>
<DataTemplate x:Key="ObjectColumnTemplate">
<ItemsControl ItemsSource="{Binding ., UpdateSourceTrigger=PropertyChanged}" ItemTemplate="{DynamicResource ObjectRowTemplate}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</UserControl.Resources>
<StackPanel>
<Canvas Background="Black" Width="{Binding CanvasWidth}" Height="600">
<Grid>
<ItemsControl ItemsSource="{Binding Path=BindedProperty, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" ItemTemplate="{DynamicResource ObjectColumnTemplate}"/>
</Grid>
</Canvas>
</StackPanel>
there is a StackPanel with a canvas inside which shows the array of array via the two defined DataTemplates, by creating a Rectangle for each "slot" in the Array.
namespace ViewModels
{
public class ViewModel : AdvancedViewModelBase
{
public CreateGameFieldViewModel()
{
ObjectClickedCommand = new Command<Object>(ObjectClicked);
Objects = new Objects[15][];
for (int i = 0; i < 15; i++)
{
Objects[i] = new Object[15];
for (int j = 0; j < 15; j++)
{
Objects[i][j] = new Object(someparams);
}
}
}
private Object _selectedObject;
private Object[][] _object;
public Object[][] Objects
{
get { return _object; }
set
{
_object = value;
RaisePropertyChanged(nameof(Objects));
}
}
public int CanvasWidth { get; set; } = 450;
public Command<OPbject> ObjectClickedCommand { get; set; }
public void ObjectClicked(Object object)
{
if (object != null)
{
_selectedObject = object;
}
}
public void OnKeyDown(KeyEventArgs e)
{
// Modify _currentObject
_currentObject.color = Brushes.Blue;
RaisePropertyChanged(nameof(Objects));
}
}
}
The property binding with the viewmodel works fine, the properties are set as defined. By clicking on a Rectangle, the object which is bound to, is now set as _selectedObject and can be modified by the arrow keys, which also works like a charm.
Since I modified one object of the array of arrays, which I am binding to the DataTemplate, I have to notify my UI which I am doing by then line RaisePropertyChanged(nameof(Objects)); (used Nuget: Catel) after the modification.
Unfortunately the UI does not get updated. I checked everything, the object in the array of arrays contains the modifications.
I guess it doesn't work because of the DataTemplates I used.
Can anyone help me?
I am facing the same issue in UWP when the ObservableCollection of the second level of the parent ObservableCollection won't update UI in DataTemplate though it has implemented INotifyPropertyChanged.
It seems like Routing does not work for the nested ObservableCollection.
I also was not able to force the method myObject.OnPropertyChanged('PropertyName').
So the solution was folllowing:
Dynamically populate Tag property of the DataTemplate using ObjectToString converter. So the Tag has a string like Author-3. Where is 3 is the ID of the Author entity and as result we have unique identifiers for all objects created on base of DataTemplate.
Within code just find all objects via Object Type and the Tag name (i.e. Author-3) and do what you need to change its any property.
And you have working UI!
In my case I will provide chunks of code and you will have whole imagination what's going on.
XAML
xmlns:myconverters="using:MyProjectFolder.Converters"
<UserControl.Resources>
<myconverters:LoaderOnlineToColorConverter x:Key="MyLoaderOnlineToColorConverter"/>
<muxc:StackLayout x:Key="UniformGridLayout2" />
<DataTemplate x:Key="UnitLoaderItemTemplate" x:DataType="x1:UnitLoader">
<Grid BorderBrush="Gray" BorderThickness="1" Margin="0,5,0,0" Padding="5,0,5,5" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="6*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<StackPanel IsDoubleTapEnabled="True" DoubleTapped="Unit_DoubleTapped" Tag="{x:Bind DeviceID}"
Grid.Column="0" Padding="2,0,2,4" Margin="0,5,0,0" Orientation="Horizontal"
BorderBrush="Gray" BorderThickness="1" ToolTipService.ToolTip="{x:Bind FullName}">
<FontIcon Tag="{x:Bind Converter={StaticResource MyDeviceIDToControlNameConverter}}"
Foreground="{x:Bind Converter={StaticResource MyLoaderOnlineToColorConverter}}"
FontFamily="Segoe MDL2 Assets" Glyph="" VerticalAlignment="Center" Margin="0,0,2,0" />
<TextBlock Text="{x:Bind DeviceName}" VerticalAlignment="Center" />
</StackPanel>
NOTE: this line Foreground="{x:Bind Converter={StaticResource MyLoaderOnlineToColorConverter}}" exactly does not work so we have another one
Tag="{x:Bind Converter={StaticResource MyDeviceIDToControlNameConverter}}"
C# The converters
public class DeviceIDToControlNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var controlName = "Unit-";
if (value is UnitLoader)
{
controlName = "Loader-" + ((UnitLoader)value).DeviceID;
}
else if (value is UnitLoader)
{
controlName = "Track-" + ((UnitTrack)value).DeviceID;
}
return controlName;
}
}
public class LoaderOnlineToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
SolidColorBrush color;
if (value is UnitLoader)
{
var isOnline = ((UnitLoader)value).IsOnline;
if (isOnline)
{
color = new SolidColorBrush(Colors.YellowGreen);
}
else
{
color = new SolidColorBrush(Colors.DarkGray);
}
}
else
{
color = new SolidColorBrush(Colors.DarkGray);
}
return color;
}
}
C# The code to change the property of all objects
string tagName = "Loader-" + unitLoader.DeviceID.ToString();
var fontIcon = FindControl<FontIcon>(this, typeof(FontIcon), tagName);
if (fontIcon != null)
{
fontIcon.Foreground = unitLoader.IsOnline ? deviceOnline : deviceOffline;
}
C# Method to search all objects via Type and Tag
public static T FindControl<T>(UIElement parent, Type targetType, string ControlName) where T : FrameworkElement
{
if (parent == null) return null;
if (parent.GetType() == targetType && ((T)parent).Tag != null && ((T)parent).Tag.ToString() == ControlName)
{
return (T)parent;
}
T result = null;
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++)
{
UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
if (FindControl<T>(child, targetType, ControlName) != null)
{
result = FindControl<T>(child, targetType, ControlName);
break;
}
}
return result;
}
Related
this is my code, The combo-box control contains text & image :
XAML codes :
<ComboBox Name="cb1"
VerticalAlignment="Center" HorizontalAlignment="Center"
Header="Abcd"
IsEditable="True"
Margin="5"
Width="120">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Icon}" Width="20" Height="20" Margin="5,0,10,0"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
C# codes :
public sealed partial class SamplePage2 : Page
{
public SamplePage2()
{
InitializeComponent();
cb1.Items.Add(new Model
{
Icon = new BitmapImage(new Uri("ms-appx:///Assets/Images/mecca.png")),
Text = "بقره"
});
cb1.Items.Add(new Model
{
Icon = new BitmapImage(new Uri("ms-appx:///Assets/Images/medina.png")),
Text = "فاتحه"
});
cb1.SelectedIndex = 0;
}
class Model
{
public BitmapImage Icon { get; set; }
public string Text { get; set; }
}
}
But when I click on the pointer button, or click inside the text..., see this image :
How I can solve this problem?
Note : I need 'IsEditable' feature [ Because I want the user to quickly reach the desired option by writing the text. ]
UWP ComboBox IsEditable does not work right
The problem is the display member is the model class, so it will not editable, for your scenario, we suggest you make a string collection as ComboBox data source. Then us image converter to set image source base on the item's content. For more please refer this case reply.
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image
Width="22"
Height="22"
Source="{Binding Converter={StaticResource ImageConverter}}"
/>
<TextBlock
Margin="10"
Text="{Binding}"
TextAlignment="Center"
/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
MyComboBox.ItemsSource = new List<string>() { "Red", "Green", "Blue" };
}
Image Converter
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string resaut = string.Empty;
switch (value.ToString())
{
case "Blue":
resaut = "ms-appx:///Assets/BlueImage.png";
break;
case "Green":
resaut = "ms-appx:///Assets/GreenImage.png";
break;
case "Red":
resaut = "ms-appx:///Assets/RedImage.png";
break;
default:
break;
}
return resaut;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
I create multiple checkbox using ItemsControl in my WPF. But I need to make a limit by 20 for checkbox that can be checked/ticked by user. How do I can check the checked checkbox?
I tried to research this as much as I can, and even binding checkbox to multiple command, but none of it is working. Below is my code to get through the checkbox that were inside the Itemscontrol. after, IsChecked.
for (int i = 0; i < ItemsControlUnitPerStrip.Items.Count; i++)
{
ContentPresenter container = (ContentPresenter)ItemsControlUnitPerStrip.ItemContainerGenerator.ContainerFromItem(ItemsControlUnitPerStrip.Items[i]);
CheckBox checkBoxChecked = container.ContentTemplate.FindName("CheckBoxUnitPerStrip", container) as CheckBox;
if (checkBoxChecked.IsChecked == true)
{
//iOPC.WriteTag(checkBoxChecked.Uid, checkBoxChecked.IsChecked);
}
}
My XAML code
<GroupBox x:Name="GroupBoxSamplingModeStrip" Header="Unit Per Strip" Grid.Row="0" Grid.Column="1">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl x:Name="ItemsControlUnitPerStrip"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.VirtualizationMode="Recycling">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="{Binding StripRowsCount}"
Columns="{Binding StripColumnsCount}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="CheckBoxUnitPerStrip"
Uid="{Binding Tag}">
<CheckBox.ToolTip>
<ToolTip x:Name="TootlTipUnitPerStrip">
<TextBlock Text="{Binding Key}"/>
</ToolTip>
</CheckBox.ToolTip>
</CheckBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</GroupBox>
Here the function code on how I generate the checkbox
private void initializeUnitPerStrip()
{
unitPerStrip = new List<UtilitiesModel>();
int totalRow = samplingModeModel.StripRows = 7;
int totalCol = samplingModeModel.StripColumn = 15;
int frontOffset = 8;
int behindOffset = 0;
for (int c = 1; c < totalCol; c++)
{
for (int r = 1; r < totalRow; r++)
{
unitPerStrip.Add(new UtilitiesModel
{
Key = $"[{c}, {r}]",
Tag = $"{UTAC_Tags.S7Connection}DB{406},X{frontOffset}.{behindOffset}"
});
}
}
ItemsControlUnitPerStrip.ItemsSource = unitPerStrip;
}
1) Binding checkbox property with notify property changed events:
public class UtilitiesModel : NotifyBase
{
private bool _IsChecked = false;
...
// Key
// Tag
...
public bool IsChecked
{
get {return _IsChecked;}
set
{
_IsChecked = value;
OnPropertyChanged("IsChecked");
}
}
}
For convenience, the part responsible for events is placed in a separate small class:
public class NotifyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
XAML changes:
..
<CheckBox x:Name="CheckBoxUnitPerStrip"
Uid="{Binding Tag}"
IsChecked="{Binding IsChecked}">
<CheckBox.ToolTip>
<ToolTip x:Name="TootlTipUnitPerStrip">
<TextBlock Text="{Binding Key}" />
</ToolTip>
</CheckBox.ToolTip>
</CheckBox>
..
2) Next we shall track events of changing state of checkboxes and add a counter for checked checkboxes;
A slight change in function:
private void initializeUnitPerStrip()
{
..
for (int c = 1; c < totalCol; c++)
{
for (int r = 1; r < totalRow; r++)
{
UtilitiesModel item = new UtilitiesModel
{
Key = "[{c}, {r}]",
Tag = "{UTAC_Tags.S7Connection}DB{406},X{frontOffset}.{behindOffset}"
};
item.PropertyChanged += PropertyChangedFunc;
unitPerStrip.Add(item);
}
}
ItemsControlUnitPerStrip.ItemsSource = unitPerStrip;
}
Add func for checking property changed events:
private void PropertyChangedFunc(object sender, PropertyChangedEventArgs e)
{
UtilitiesModel obj = sender as UtilitiesModel;
if(obj==null)return;
if (e.PropertyName == "IsChecked")
{
iCount1 = obj.IsChecked ? iCount1 + 1 : iCount1 - 1;
if (iCount1 > 19) //Block checking
{
obj.IsChecked = false;
}
}
}
Where iCount1 - is a counter checked checkboxes, just declare it anywhere, for example in samplingModeModel
This answer uses MVVM, so the names of your controls in XAML have been removed as they are not needed in MVVM. Your XAML would look like this:
<Button Content="Count CheckBoxes" Command="{Binding CommandCount}"
HorizontalAlignment="Left"/>
<GroupBox Header="Unit Per Strip" Grid.Row="0" Grid.Column="1">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.VirtualizationMode="Recycling"
ItemsSource="{Binding Path=UnitPerStrip}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="{Binding StripRowsCount}"
Columns="{Binding StripColumnsCount}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Uid="{Binding Tag}"
IsChecked="{Binding IsChecked}">
<CheckBox.ToolTip>
<ToolTip >
<TextBlock Text="{Binding Key}"/>
</ToolTip>
</CheckBox.ToolTip>
</CheckBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</GroupBox>
The only real difference in the XAML is adding the binding to the 'IsChecked' property in the CheckBox, and setting up a binding to a property called 'UnitPerStrip' for the ItemsSource of the ItemsControl.
In the ViewModel then, you need to set up the UnitPerStrip property:
private List<UtilitiesModel> unitPerStrip;
public List<UtilitiesModel> UnitPerStrip
{
get
{
return unitPerStrip;
}
set
{
if (value != unitPerStrip)
{
unitPerStrip = value;
NotifyPropertyChanged("UnitPerStrip");
}
}
}
The UtilitiesModel class needs a new property called IsChecked to keep track of when the CheckBox is checked. That way you don't have to muck about with messy UI code. It can all be done neatly in the back-end data.
public class UtilitiesModel
{
public string Key { get; set; }
public string Tag { get; set; }
public bool IsChecked { get; set; }
}
The code for generating the CheckBoxes doesn't change a lot. You just need to make sure to add in the IsChecked property and then assign the results to the UnitPerStrip property when finished.
private void initializeUnitPerStrip()
{
List<UtilitiesModel> ups = new List<UtilitiesModel>();
int totalRow = samplingModeModel.StripRows = 7;
int totalCol = samplingModeModel.StripColumn = 15;
int frontOffset = 8;
int behindOffset = 0;
for (int c = 1; c < totalCol; c++)
{
for (int r = 1; r < totalRow; r++)
{
ups.Add(new UtilitiesModel
{
Key = $"[{c}, {r}]",
Tag = $"{UTAC_Tags.S7Connection}DB{406},X{frontOffset}.{behindOffset}",
IsChecked = false;
});
}
}
UnitPerStrip = ups;
}
Then the code to check how many CheckBoxes are checked is very straightforward. It only examines the data in the ViewModel and never has to worry about messing with any of the messiness of the UI:
private void Count()
{
int count = 0;
foreach (UtilitiesModel item in UnitPerStrip)
{
if (item.IsChecked) count++;
}
MessageBox.Show(count.ToString());
}
In case you don't like to add a special IsChecked property to your model you could use a IValueConverter.
A property like IsChecked is view related and shouldn't be part of the view model (if you can avoid it). When you change the control that binds to the view model you might also need to change this property or rename it (e.g. IsExpanded etc.).
I recommend to avoid properties that reflect a visual state inside a view model in general. Your view model would become bloated if adding properties like IsVisible, IsPressed, IsToggled. This properties rather belong to a Control.
The converter (or DataTrigger) approach leaves your binding data models unchanged (with data related properties only). To keep the view model clean and free from UI logic like adjusting properties like IsVisible or IsChecked to reflect e.g. reordering of the collection to the view (e.g. insert or sort operations), all UI logic and visual details like enabling or disabling the controls
should be handled by converters and triggers only:
<!-- Decalare the converter and set the MaxCount property -->
<Window.Resources>
<local:ItemCountToBoolenaConverter x:Key="ItemCountToBoolenaConverter"
MaxCount="20" />
</Window.Resources>
<! -- The actual DataTemplate -->
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="CheckBoxUnitPerStrip"
IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBoxItem}, Converter={StaticResource ItemCountToBoolenaConverter}}">
<CheckBox.ToolTip>
<ToolTip x:Name="TootlTipUnitPerStrip">
<TextBlock Text="{Binding Key}" />
</ToolTip>
</CheckBox.ToolTip>
</CheckBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
The ItemCountToBoolenaConverter:
[ValueConversion(typeof(ListBoxItem), typeof(bool))]
class ItemCountToBoolenaConverter : IValueConverter
{
public int MaxCount { get; set; }
#region Implementation of IValueConverter
/// <inheritdoc />
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is ListBoxItem itemContainer && TryFindParentElement(itemContainer, out ItemsControl parentItemsControl))
{
return parentItemsControl.Items.IndexOf(itemContainer.Content) < this.MaxCount;
}
return Binding.DoNothing;
}
/// <inheritdoc />
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
// Consider to make this an Extension Method for DependencyObject
private bool TryFindVisualParent<TParent>(DependencyObject child, out TParent resultElement) where TParent : DependencyObject
{
resultElement = null;
if (child == null)
return false;
DependencyObject parentElement = VisualTreeHelper.GetParent(child);
if (parentElement is TParent)
{
resultElement = parentElement as TParent;
return true;
}
return TryFindVisualParent(parentElement, out resultElement);
}
}
This question already has answers here:
How to use DataTemplateSelector with ContentControl to display different controls based on the view-model?
(2 answers)
Closed 4 years ago.
I'm trying to write a simple dialog that would accept a value in a SpinEdit or a text in a TextEdit. I'm using multiple VMs and I made a selector that should view a proper control based on the logic in the c++/cli file.
XAML:
xmlns:local="clr-namespace:asd"
Title="{Binding Path=Title, Mode=OneTime}"
<dx:DXWindow.Resources>
<DataTemplate x:Key="TInputValueVM" DataType="{x:Type local:TInputValueVM}">
<dxe:SpinEdit Height="23" Width="200"
Text="{Binding Value, Mode=TwoWay}"
Mask="{Binding Mask, Mode=OneWay}"
MaxLength="{Binding Path=InputLength}" />
</DataTemplate>
<DataTemplate x:Key="TInputTextVM" DataType="{x:Type local:TInputTextVM}">
<dxe:TextEdit Height="23" Width="200"
Text="{Binding Value, Mode=TwoWay}"
MaskType="RegEx" Mask="{Binding Mask, Mode=OneWay}"
MaxLength="{Binding Path=InputLength}"/>
</DataTemplate>
<local:PropertyDataTemplateSelector x:Key="templateSelector"
DataTemplate_Value="{StaticResource TInputValueVM}"
DataTemplate_Text="{StaticResource TInputTextVM}" />
</dx:DXWindow.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" >
<Label x:Uid="Label" MinHeight="24" MinWidth="60" Content="Value" />
<ContentControl Content="{Binding Path=Whoami}" ContentTemplateSelector="{StaticResource templateSelector}" />
</StackPanel>
<StackPanel Grid.Row="1" x:Uid="OKCancel_Buttons" Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Bottom">
<Button Height="23" x:Name="OK_Button" Click="OK_Click" Content="OK" IsDefault="True" HorizontalAlignment="Right" MinWidth="95" />
<Button Height="23" x:Name="Cancel_Button" Click="Cancel_Click" Content="Cancel" HorizontalAlignment="Right" MinWidth="95" />
</StackPanel>
</Grid>
In c# I have a base VM and two VMS that extend it, one for values and one for text. The rest of the properties stay the same.
C#
namespace asd
{
public class TInputBaseVM : ViewModelBase
{
private string m_sTitle;
private string m_sMask;
private int m_nInputLenght;
private string m_sWhoami;
public TInputBaseVM(string A_sTitle, string A_sMask, int A_nInputLength)
{
m_sTitle = A_sTitle;
m_sMask = A_sMask;
m_nInputLenght = A_nInputLength;
}
protected string Title
{
get { return m_sTitle; }
set { SetProperty(ref m_sTitle, value, () => Title); }
}
protected string Mask
{
get { return m_sMask; }
set { SetProperty(ref m_sMask, value, () => Mask); }
}
protected int InputLength
{
get { return m_nInputLenght; }
set { SetProperty(ref m_nInputLenght, value, () => InputLength); }
}
protected string Whoami
{
get { return m_sWhoami; }
set { SetProperty(ref m_sWhoami, value, () => Whoami); }
}
}
public class TInputValueVM : TInputBaseVM
{
public TInputValueVM(string A_sTitle, string A_sMask, int A_nInputLength, double A_nValue) : base(A_sTitle, A_sMask, A_nInputLength)
{
Value = A_nValue;
Whoami = "Value";
}
private double m_nValue;
public double Value
{
get { return m_nValue; }
set { SetProperty(ref m_nValue, value, () => Value); }
}
}
public class TInputTextVM : TInputBaseVM
{
public TInputTextVM(string A_sTitle, string A_sMask, int A_nInputLength, string A_sValue) : base(A_sTitle, A_sMask, A_nInputLength)
{
Value = A_sValue;
Whoami = "Text";
}
private string m_sValue;
public string Value
{
get { return m_sValue; }
set { SetProperty(ref m_sValue, value, () => Value); }
}
}
public class PropertyDataTemplateSelector : DataTemplateSelector
{
public DataTemplate DataTemplate_Value { get; set; }
public DataTemplate DataTemplate_Text { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var selector = item as string;
if(selector == "Value")
return DataTemplate_Value;
return DataTemplate_Text;
}
}
}
In c++/cli I create an object of a proper VM and I'd like the WPF to automatically update the view to either spinedit or textedit, however I'm not sure how to properly bind the properties from the C#. If I explicitly type 'Value' in the Content property of the ContentControl then it displays the spinEdit but I don't know how to bind it so it automatically takes the correct property.
EDIT: I'm adding c++/cli code to show how I choose different VMs
C++/cli:
bool TSignalNumberPositionDialogCLR::StartDialog(TSignalNumberPositionSupport& A_Attributes, HWND A_hwndParent, LPTSTR String)
{
try
{
TInputValueVM ^oExchange_Value;
TInputTextVM ^oExchange_Text;
int inputFormat = A_Attributes.GetInputFormat();
if(inputFormat)
oExchange_Text = gcnew TInputTextVM(gcnew System::String(A_Attributes.GetTitle()), gcnew System::String(A_Attributes.GetMask()),
A_Attributes.GetInputLength(), gcnew System::String(A_Attributes.GetInitialText()));
else
oExchange_Value = gcnew TInputValueVM(gcnew System::String(A_Attributes.GetTitle()), gcnew System::String(A_Attributes.GetMask()),
A_Attributes.GetInputLength(), A_Attributes.GetInitialValue());
Dialogs::TSignalNumberPositionDialog^ dialog = gcnew Dialogs::TSignalNumberPositionDialog();
if(inputFormat)
dialog->DataContext = oExchange_Text;
else
dialog->DataContext = oExchange_Value;
dialog->ShowDialog();
if(dialog->DialogResult)
{
CString nValue;
if(inputFormat)
nValue = oExchange_Text->Value;
else
nValue = ((Decimal)oExchange_Value->Value).ToString("F2", CultureInfo::InvariantCulture);
A_Attributes.UpdateValue(nValue, String, A_Attributes.GetInputLength());
return true;
}
return false;
}
catch(Exception^ e)
{
e;
}
}
based on the 'inputFormat' variable I want to display different controls in the dialog.
EDIT: Based on #Clemens comments I got rid of the selector sectionand the x:Key property in the DataTemplates. I changed the content opf the Content property to Content="{Binding}" and it somehow works. The moment I create a VM it selects the correct one.
Based on your comment. Let me improve my answer. As you are facing issue in VM selection. so plesae concentrate how I assigned VM to datatemplate. Although it is done in very basic way, you can handle it if you you are using MVVM packages.
I have created 2 data template and 2 vms and each vm is bound to datatemplate. To verify, I have a combobox, which will select datatemplate based on selected value.
Here is Sample VM
public class VM : System.ComponentModel.INotifyPropertyChanged
{
private string title;
private SolidColorBrush background;
public string Title { get => title; set { title = value; RaisePropertyChanged(); } }
public SolidColorBrush Background { get => background; set { background = value; RaisePropertyChanged(); } }
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
public class VM1: VM
{
public VM1()
{
Title = "This is VM1";
Background = Brushes.Yellow;
}
}
public class VM2: VM
{
public VM2()
{
Title = "This is VM2";
Background = Brushes.Orange;
}
}
Now check for resources
<local:VM1 x:Key="VM1"/>
<local:VM2 x:Key="VM2"/>
<DataTemplate x:Key="DT1">
<Grid DataContext="{StaticResource VM1}">
<TextBlock Text="{Binding Title}" Background="{Binding Background}"/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="DT2">
<Grid DataContext="{StaticResource VM2}">
<TextBlock Text="{Binding Title}" Background="{Binding Background}"/>
</Grid>
</DataTemplate>
<Style TargetType="ContentControl" x:Key="contentStyle">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=cmbo, Path=SelectedValue}" Value="Template1">
<Setter Property="ContentTemplate" Value="{StaticResource DT1}" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=cmbo, Path=SelectedValue}" Value="Template2">
<Setter Property="ContentTemplate" Value="{StaticResource DT2}" />
</DataTrigger>
</Style.Triggers>
</Style>
and finally I have combobox and content control just to verify
<ComboBox Name="cmbo"/>
<ContentControl Style="{StaticResource contentStyle}"/>
where cmbo.ItemsSource = new List { "Template1", "Template2" };
Hope you got the point
Prerequisites: .NET 4.5.1
I have three TreeView controls that display three filtered variants of single collection instance. When I try to apply a filter on Items collection of one of controls this filter propagates to other controls automatically which prevents me to use different filters on different controls.
Is there any way to achieve the same result without having to maintain three instances of collections at once?
An example that shows the problem follows below. First two ListViews are bound to the same collection instance directly. Third one is bound to that instance through CompositeCollection. And the fourth is bound to independent collection. When I press "Set Filter" button ItemsControl.Items.Filter property if first ListView is set to IsAllowedItem method of WTest window. After this second istView.Items.Filter property somehow points to the same method while third and fourth ListView returns null. Another effect is that though third ListView shows null filter its collection is still filtered as you can see if you run the example. This very strange effect arises from the behavior of ItemCollection class that when based on ItemsSource property of owner element acquires underlying CollectionView from some application-wide storage via CollectionViewSource.GetDefaultCollectionView method. I don't know the reason of this implementation but suspect suspect that it's performance.
Test window WTest.xaml:
<Window x:Class="Local.WTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:c="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:local="clr-namespace:Local"
Name="_WTest" Title="WTest" Height="300" Width="600">
<Window.Resources>
<c:ArrayList x:Key="MyArray">
<s:String>Letter A</s:String>
<s:String>Letter B</s:String>
<s:String>Letter C</s:String>
</c:ArrayList>
<CompositeCollection x:Key="MyCollection" >
<CollectionContainer Collection="{StaticResource ResourceKey=MyArray}"/>
</CompositeCollection>
<c:ArrayList x:Key="AnotherArray">
<s:String>Letter A</s:String>
<s:String>Letter B</s:String>
<s:String>Letter C</s:String>
</c:ArrayList>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Name="FilterLabel1"/>
<TextBlock Grid.Row="0" Grid.Column="1" Name="FilterLabel2"/>
<TextBlock Grid.Row="0" Grid.Column="2" Name="FilterLabel3"/>
<TextBlock Grid.Row="0" Grid.Column="3" Name="FilterLabel4"/>
<ListView Grid.Row="1" Grid.Column="0" Name="View1" ItemsSource="{StaticResource ResourceKey=MyArray}"/>
<ListView Grid.Row="1" Grid.Column="1" Name="View2" ItemsSource="{StaticResource ResourceKey=MyArray}"/>
<ListView Grid.Row="1" Grid.Column="2" Name="View3" ItemsSource="{StaticResource ResourceKey=MyCollection}"/>
<ListView Grid.Row="1" Grid.Column="3" Name="View4" ItemsSource="{StaticResource ResourceKey=AnotherArray}"/>
<Button Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="4" Content="Set Filter" Click="OnSetFilterButtonClick"/>
</Grid>
</Window>
Code behind WTest.xaml.cs
namespace Local
{
using System.Windows;
public partial class WTest : Window
{
public WTest()
{
InitializeComponent();
UpdateFilterLabels();
}
private bool IsAllowedItem(object item)
{
return "Letter A" == (string)item;
}
private void OnSetFilterButtonClick(object sender, RoutedEventArgs e)
{
View1.Items.Filter = IsAllowedItem;
UpdateFilterLabels();
}
private void UpdateFilterLabels()
{
FilterLabel1.Text = (null == View1.Items.Filter) ? "No Filter" : View1.Items.Filter.Method.Name;
FilterLabel2.Text = (null == View2.Items.Filter) ? "No Filter" : View2.Items.Filter.Method.Name;
FilterLabel3.Text = (null == View3.Items.Filter) ? "No Filter" : View3.Items.Filter.Method.Name;
FilterLabel4.Text = (null == View4.Items.Filter) ? "No Filter" : View4.Items.Filter.Method.Name;
}
}
}
And result after "Set Filter" button is clicked:
Example: result of clicking "Set Filter" button
Create CollectionViewSource as a Resource.
<CollectionViewSource x:Key="CVSKey" Source="{DynamicResource MyArray}"/>
Use this CollectionViewSource as your ItemsSource . Replace your View1 as :
<!--<ListView Grid.Row="1" Grid.Column="0" Name="View1" ItemsSource="{DynamicResource ResourceKey=MyArray}"/>-->
<ListView Grid.Row="1" Grid.Column="0" Name="View1" ItemsSource="{Binding Source={StaticResource ResourceKey=CVSKey}}"/>
Thats it, now everything will work as you want it to.
Additionally, now you can apply filtering to this CollectionViewSource instead of View1 :
((CollectionViewSource)this.Resources["CVSKey"]).Filter += List_Filter;
void List_Filter(object sender, FilterEventArgs e)
{
e.Accepted = (e.Item.ToString() == "Letter A") ? true : false;
}
Create separate CollectionViewSource for separate ListBoxes to create separate views from same underlying collection.
Search google for CollectionViewSource.
Change the OnSetFilterButtonClick Method as below
private void OnSetFilterButtonClick(object sender, RoutedEventArgs e)
{
//Create a new listview by the ItemsSource,Apply Filter to the new listview
ListCollectionView listView = new ListCollectionView(View1.ItemsSource as IList);
listView.Filter = IsAllowedItem;
View1.ItemsSource = listView;
UpdateFilterLabels();
}
I found a simple solution that does not require creating a CollectionViewSource resource in XAML or a ListCollectionView in code for every collection that needs its own filter.
My solution is to use an ValueConverter that converts the ItemsSource source to a CollectionViewSource.View
ItemsSourceConverter:
[ValueConversion(typeof(IEnumerable), typeof(IEnumerable))]
public class ItemsSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is IEnumerable itemsSource && itemsSource != null)
{
return new CollectionViewSource() { Source = itemsSource }.View;
}
else
{
throw new Exception($"Value must be an {nameof(IEnumerable)}");
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
XAML:
<Window ...>
<Window.Resources>
<local:ItemsSourceConverter x:Key="ItemsSourceConverter"/>
</Window.Resources>
...
<ItemsControl Name="View1",
ItemsSource="{Binding Collection1, Converter={StaticResource ItemsSourceConverter}, Mode=OneWay}" />
<ItemsControl Name="View2",
ItemsSource="{Binding Collection3, Converter={StaticResource ItemsSourceConverter}, Mode=OneWay}" />
<ItemsControl Name="View3",
ItemsSource="{Binding Collection3, Converter={StaticResource ItemsSourceConverter}, Mode=OneWay}" />
</Window>
Code behind:
public partial class MainWindow : Window
{
ObservableCollection<DataClass> Collection1 { get; private set; }
ObservableCollection<DataClass> Collection2 { get; private set; }
ObservableCollection<DataClass> Collection3 { get; private set; }
public MainWindow()
{
InitializeComponent();
}
...
private void SetFilters()
{
View1.Filter = (item) =>
{
// Filter logic
};
View2.Filter = (item) =>
{
// Filter logic
};
View2.Filter = (item) =>
{
// Filter logic
};
}
...
}
MVVM ItemsControl with Filter binding
If we want to use the above solution with MVVM, we can create an attached property to bind the ItemsControl.Filter to a filter defined in the ViewModel.
Filter attached property:
public static class CollectionViewExtensions
{
public static readonly DependencyProperty FilterProperty = DependencyProperty.RegisterAttached(
"Filter",
typeof(Predicate<object>),
typeof(CollectionViewExtensions),
new PropertyMetadata(default(Predicate<object>), OnFilterChanged));
public static void SetFilter(ItemsControl element, Predicate<object> value)
{
element.SetValue(FilterProperty, value);
}
public static Predicate<object> GetFilter(ItemsControl element)
{
return (Predicate<object>)element.GetValue(FilterProperty);
}
private static void OnFilterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is ItemsControl itemsControl && itemsControl.Items.CanFilter)
{
if (e.OldValue is Predicate<object> oldPredicate)
{
itemsControl.Items.Filter -= oldPredicate;
}
if (e.NewValue is Predicate<object> newPredicate)
{
itemsControl.Items.Filter += newPredicate;
}
}
}
}
Source: https://stackoverflow.com/a/39438710/10927863
XAML:
<Window ...>
<Window.Resources>
<local:ItemsSourceConverter x:Key="ItemsSourceConverter"/>
</Window.Resources>
...
<ItemsControl ItemsSource="{Binding Collection1, Converter={StaticResource ItemsSourceConverter}, Mode=OneWay}"
local:CollectionViewExtensions.Filter="{Binding Filter1}"/>
<ItemsControl ItemsSource="{Binding Collection3, Converter={StaticResource ItemsSourceConverter}, Mode=OneWay}"
local:CollectionViewExtensions.Filter="{Binding Filter2}"/>
<ItemsControl ItemsSource="{Binding Collection3, Converter={StaticResource ItemsSourceConverter}, Mode=OneWay}"
local:CollectionViewExtensions.Filter="{Binding Filter3}"/>
</Window>
ViewModel:
public class ViewModel
{
ObservableCollection<DataClass> Collection1 { get; private set; }
ObservableCollection<DataClass> Collection2 { get; private set; }
ObservableCollection<DataClass> Collection3 { get; private set; }
public Predicate<object> Filter1 { get; private set; }
public Predicate<object> Filter2 { get; private set; }
public Predicate<object> Filter3 { get; private set; }
...
private void SetFilters()
{
Filter1 = (item) =>
{
// Filter logic
};
Filter2 = (item) =>
{
// Filter logic
};
Filter3 = (item) =>
{
// Filter logic
};
}
...
}
I bind the Rectangle Fill property on bool value (Fill="{Binding Path=IsSelected, Converter={StaticResource rectangleFillConverter}}") and it throws a null exception. I checked the value of property (IsSelected) is not null. When I remove Converter from Fill property it works. Here is my code:
xaml
<Rectangle Width="{Binding Duration}" Height="20" Tag="{Binding .}" IsEnabled="{Binding Path=IsEnabled}" Fill="{Binding Path=IsSelected, Converter={StaticResource rectangleFillConverter}}" ToolTip="{Binding Path=Shift}" MouseDown="LabelShift_MouseDown"></Rectangle>
Converter
public class RectangleControlFillConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
SolidColorBrush brush;
bool b= (bool)value;
if (b)
brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#5C8FFF"));
else
brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#73E34D"));
return brush;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Static Resource
<converters:RectangleControlFillConverter x:Key="rectangleFillConverter"/>
Property
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
OnPropertyChanged("IsSelected");
}
}
ItemsControl where is rectangle and this converter works Converter={StaticResource timeToPositionConverter}}"
<ItemsControl Name="icSchedule" ItemsSource="{Binding .}" Grid.Row="1" Grid.Column="1">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Margin="0"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding Path=icw}" Tag="{Binding .}" Margin="0,10,0,0"><!--Margin="3"Grid.Row="1" Grid.Column="1" Background="DarkGray" BorderThickness="1" BorderBrush="White"-->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type ContentPresenter}">
<Setter Property="Canvas.Left" Value="{Binding Path=Start, Converter={StaticResource timeToPositionConverter}}" />
<Setter Property="Canvas.Top" Value="{Binding Path=Index}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="TimeLineEntry">
<Border BorderThickness="1" BorderBrush="DarkGray">
<Rectangle Width="{Binding Duration}" Height="20" Tag="{Binding .}" IsEnabled="{Binding Path=IsEnabled}" Fill="{Binding Path=IsSelected, Converter={StaticResource rectangleFillConverter}}" ToolTip="{Binding Path=Shift}" MouseDown="LabelShift_MouseDown">
</Rectangle>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
This is the class on wich object is rectangle binding (icw is a list of that objects)
public partial class ScheduleItem
{
public string Shift
{
get
{
//string s = ((DateTime)DateFrom).ToString("dd.MM.yyyy") + " " + ((TimeSpan)TimeFrom).ToString() + " - " + ((DateTime)DateTo).ToString("dd.MM.yyyy") + " " + ((TimeSpan)TimeTo).ToString();
String s = String.Format("{0}.{1} {2}:{3} - {4}.{5} {6}:{7}", FullDateFrom.Day, FullDateFrom.Month, FullDateFrom.Hour, FullDateFrom.Minute, FullDateTo.Day, FullDateTo.Month, FullDateTo.Hour, FullDateTo.Minute);
return s;
}
}
private DateTime FullDateFrom
{
get
{
DateTime dt = ((DateTime)DateFrom).AddHours(((TimeSpan)TimeFrom).Hours).AddMinutes(((TimeSpan)TimeFrom).Minutes);
return dt;
}
}
private DateTime FullDateTo
{
get
{
DateTime dt = ((DateTime)DateTo).AddHours(((TimeSpan)TimeTo).Hours).AddMinutes(((TimeSpan)TimeTo).Minutes);
return dt;
}
}
public string Name { get; set; }
public DateTime Start { get { return FullDateFrom; } }
private int index;
public int Index
{
get
{
if (CampaignPerson != null)
return CampaignPerson.Index;
else
return index;
}
set
{
index = value;
}
}
public int Duration
{
get
{
TimeSpan dt = FullDateTo - FullDateFrom;
return (dt.Days* 92) + (dt.Hours*4);
}
}
public bool IsEnabled
{
get { return (FullDateFrom > DateTime.Now); }
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
OnPropertyChanged("IsSelected");
}
}
#region setters
partial void OnTimeFromChanged()
{
OnPropertyChanged("Duration");
OnPropertyChanged("Start");
}
partial void OnTimeToChanged()
{
OnPropertyChanged("Duration");
OnPropertyChanged("Start");
}
partial void OnDateFromChanged()
{
OnPropertyChanged("Duration");
OnPropertyChanged("Start");
}
partial void OnDateToChanged()
{
OnPropertyChanged("Duration");
OnPropertyChanged("Start");
}
#endregion
}
ViewModel Class The icShedule is Binding on collection of this Class
public class ScheduleExtension
{
public ICollectionView icw {get; set;}
public ScheduleExtension(CampaignPerson cp)
{
campainPerson = cp;
scheduleItemsList.CollectionChanged += new NotifyCollectionChangedEventHandler(_scheduleItemsList_CollectionChanged);
icw = CollectionViewSource.GetDefaultView(scheduleItemsList);
icw.Filter = ScheduleFilter;
}
private CampaignPerson _campainPerson;
public CampaignPerson campainPerson
{
get { return _campainPerson; }
set
{
_campainPerson = value;
scheduleItemsList = new ObservableCollection<ScheduleItem>(_campainPerson.ScheduleItem.Where(p=>p.active));
}
}
private DateTime _currentDate;
public DateTime CurrentDate
{
get { return _currentDate; }
set
{
_currentDate = value;
icw.Refresh();
//CurrrentScheduleItemsList = new ObservableCollection<ScheduleItem>(scheduleItemsList.Where(p => p.active && ((DateTime)p.DateFrom).Month == CurrentDate.Month && ((DateTime)p.DateFrom).Year == CurrentDate.Year));
//OnPropertyChanged("CurrentScheduleItemsList");
}
}
public ObservableCollection<ScheduleItem> scheduleItemsList;
void _scheduleItemsList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
}
private bool ScheduleFilter(object item)
{
if (CurrentDate != null)
{
ScheduleItem si = item as ScheduleItem;
return (CurrentDate.Month == ((DateTime)si.DateFrom).Month && CurrentDate.Year == ((DateTime)si.DateFrom).Year);
}
return false;
}
}
Try changing the <DataTemplate DataType="TimeLineEntry"> to <DataTemplate DataType="ScheduleItem">. Maybe ScheduleItem is a TimeLineEntry (you posted only one part of a partial class), but try if it works.
The problem could also be caused by the way you are handling the collection. In the constructor you say:
icw = CollectionViewSource.GetDefaultView(scheduleItemsList);
icw.Filter = ScheduleFilter;
And then in the campainPerson property you say:
scheduleItemsList = new ObservableCollection<ScheduleItem>(_campainPerson.ScheduleItem.Where(p=>p.active));
You have to either use the same collection object (by clearing it and adding new items), or by creating new ICollectionView and assigning it to icw (so you'd have to repeat the two lines from constructor after creating new ObservableCollection). Try that too.
I dont think problem is from converter, even if all work fine when you remove it. This is my test app.
MainWindow.xaml
<Window x:Class="MVVMTests.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:MVVMTests"
Background="{StaticResource {x:Static SystemColors.ControlBrushKey}}"
>
<Window.Resources>
<ResourceDictionary>
<local:RectangleControlFillConverter x:Key="rectangleFillConverter" />
</ResourceDictionary>
</Window.Resources>
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<CheckBox Content="toto" IsChecked="{Binding IsSelected}" />
<Rectangle Fill="{Binding Path=IsSelected, Converter={StaticResource rectangleFillConverter}}" Grid.Row="1" />
</Grid>
</Window>
The ViewModel
namespace MVVMTests
{
public class MainWindowViewModel : NotificationObject
{
private Boolean isSelected;
public MainWindowViewModel()
{
isSelected = true;
}
public Boolean IsSelected
{
get { return this.isSelected; }
set
{
this.isSelected = value;
this.RaisePropertyChanged<Boolean>(() => IsSelected);
}
}
}
}
and the conveter
namespace MVVMTests
{
[ValueConversion(typeof(Boolean), typeof(SolidColorBrush))]
public class RectangleControlFillConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
SolidColorBrush brush;
bool b = (bool)value;
if (b)
brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#5C8FFF"));
else
brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#73E34D"));
return brush;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
With this simple code, we can see that the converter is not the problem (window switch ugly blue / ugly green), and binding works fine.
That's not a solution, but that's show us the problem is elsewhere ...
Converter in rectangle still doesnt work on any property.
This is working for me Fill="{Binding Path=CurrentColor}"
and this change in ScheduleItem
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
if(_isSelected)
CurrentColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#73E34D"));
else
CurrentColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#5C8FFF"));
OnPropertyChanged("CurrentColor");
}
}
private SolidColorBrush _currentColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#5C8FFF"));
public SolidColorBrush CurrentColor
{
get { return _currentColor; }
set { _currentColor = value; }
}
Thanks guys for your time and your suggestion.