I will show you my demo to use Converter in ResourceDictionary.
Step 1: Create a model named MyModel which used for binding data to CheckBox.
public class MyModel: INotifyPropertyChanged
{
public string Name { get; set; }
public bool StatusForCheckBox { get; set; }
public string myBrushes;
public string MyBrushes
{
get { return myBrushes; }
set
{
myBrushes = value;
NotifyPropertyChanged("MyBrushes");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Step 2:Create a list for CheckBox in the MainWindow.xaml
<Grid>
<ListBox x:Name="myList" Width="400" Height="400" HorizontalAlignment="Right">
<ListBox.ItemTemplate>
<DataTemplate >
<CheckBox Content="{Binding Name,Mode=TwoWay}" IsChecked="{Binding StatusForCheckBox,Mode=TwoWay}" Background="{Binding MyBrushes,Mode=TwoWay}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Step 3: Binding the data for the list in MainWindow.xaml.cs:
public MainWindow()
{
InitializeComponent();
ObservableCollection<MyModel> lt = new ObservableCollection<MyModel>()
{
new MyModel{Name="Test1",StatusForCheckBox=false },
new MyModel{Name="Test2",StatusForCheckBox=true },
new MyModel{Name="Test3",StatusForCheckBox=false}
};
myList.ItemsSource = lt;
}
Step 4: Create a Converter named MyConverter, and its code is:
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
MyModel model = value as MyModel;
bool bValue = model.StatusForCheckBox;
if (bValue != true)
{
model.MyBrushes = "Red";
return model;
}
else
{
model.MyBrushes = "Yellow";
return model;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Step 5:Add the style in ResourceDictionary:
<Application.Resources>
<Style TargetType="CheckBox">
<Setter Property="Content">
<Setter.Value>
<Binding>
<Binding.Converter>
<local:MyConverter></local:MyConverter>
</Binding.Converter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
Then you can get the result picture:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.