How to properly use radiobutton checked event in mvvm pattern? - wpf

When a particular radiobutton is checked/clicked on I want to write some specific text for each of those radiobuttons in a particular textblock. How do I do that following the MVVM pattern ?
In my main viewmodel I have the following code...
public ICommand MyCommand { get; set; }
private string _txt;
public string Txt
{
get
{
return _txt;
}
set
{
_txt = value;
OnPropertyChanged("Txt");
}
}
private bool canexecutemethod(object parameter)
{
if (parameter != null)
{
return true;
}
else
{
return false;
}
}
private void executemethod(object parameter)
{
//what to do here;
}
public MainViewModel()
{
MyCommand = new RelayCommand(executemethod);
}
Also in the xaml:
<RadioButton VerticalAlignment="Center" Margin="15" Content="Name" Command="{Binding MyCommand}"/>
<RadioButton VerticalAlignment="Center" Margin="15" Content="Age" Command="{Binding MyCommand}"/>
<RadioButton VerticalAlignment="Center" Margin="15" Content="DOB" Command="{Binding MyCommand}"/>
<TextBlock Margin="5" Height="30" Width="150" Foreground="Red" Text="{Binding Txt, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
Say when the first radiobutton is checked the textblock text should show some text like
Please enter a name
, when the second radiobutton is checked the textblock text should show some text like
Please enter a valid age/integer value
and so on...

it can be done without view model participation:
<RadioButton VerticalAlignment="Center" Margin="15" Content="Name" Name="chkName"/>
<RadioButton VerticalAlignment="Center" Margin="15" Content="Age" Name="chkAge"/>
<RadioButton VerticalAlignment="Center" Margin="15" Content="DOB" Name="chkDob"/>
<TextBlock Margin="5" Height="30" Width="150" Foreground="Red">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=chkName,Path=IsChecked}" Value="True">
<Setter Property="Text" Value="Please enter a name"/>
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=chkAge,Path=IsChecked}" Value="True">
<Setter Property="Text" Value="Please enter a valid age/integer value"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>

Related

Combine design time menu elements into databound menu item binding

Hopefully I got the vernacular right on my question so I don't throw people completely off.
I have a menu that is data bound and using a HierarchicalDataTemplate that handles the various nested types in my binding object. So far everything is working fantastically; but now I would like to add a couple additional menu items to menu items of a certain type, but of course that breaks the binding as I cannot bind to a collection that already contains elements. CompositeCollection seems to be what I am looking for but I keep running into syntax errors when trying to apply that to my HierarchicalDataTemplate.
<Menu.Resources>
<HierarchicalDataTemplate DataType="{x:Type ODIF:PluginContainer}" ItemsSource="{Binding Instance.Devices}">
<HierarchicalDataTemplate.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Instance.Devices}"/>
<MenuItem>One more item!</MenuItem>
<MenuItem>Two more items!</MenuItem>
</CompositeCollection>
</HierarchicalDataTemplate.ItemsSource>
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<Image Source="{Binding PluginIcon}" Width="16" Height="16">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding PluginIcon}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<TextBlock Text="{Binding PluginName}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type ODIF:Device}" ItemsSource="{Binding InputChannels}">
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal">
<Image Source="{Binding StatusIcon}" Width="16" Height="16">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding StatusIcon}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<TextBlock Text="{Binding DeviceName}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type ODIF:DeviceChannel}">
<local:ChannelBox Channel="{Binding}" Width="200" Click="ChannelClicked"/>
</HierarchicalDataTemplate>
</Menu.Resources>
This throws:
The specified value cannot be assigned. The following type was
expected: "BindingBase".
and
Property 'ItemsSource' does not support values of type 'CompositeCollection'.
I guess you have to use a converter for solving your issue.
Let's suppose that MenuModel is a class which represents a menu item. It is really simple:
public class MenuModel
{
private List<MenuModel> children = new List<MenuModel>();
public string Description { get; set; }
public IList Children
{
get
{
return children;
}
}
}
Now we have our XAML:
<Window.Resources>
<collections:ArrayList x:Key="someOtherMenus">
<local:MenuModel Description="Menu A">
<local:MenuModel.Children>
<local:MenuModel Description="SubMenu i" />
<local:MenuModel Description="SubMenu ii" />
</local:MenuModel.Children>
</local:MenuModel>
<local:MenuModel Description="Menu B" />
</collections:ArrayList>
</Window.Resources>
<DockPanel>
<Menu DockPanel.Dock="Top" Margin="3" ItemsSource="{Binding MenuModels}">
<Menu.ItemTemplate>
<HierarchicalDataTemplate>
<HierarchicalDataTemplate.ItemsSource>
<Binding ConverterParameter="someOtherMenus">
<Binding.Converter>
<local:CompositeCollectionConverter />
</Binding.Converter>
</Binding>
</HierarchicalDataTemplate.ItemsSource>
<TextBlock Text="{Binding Description}" Margin="3" />
</HierarchicalDataTemplate>
</Menu.ItemTemplate>
</Menu>
<TextBlock Text="text" Margin="10" />
</DockPanel>
So now we can consider the converter implementation:
public class CompositeCollectionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
MenuModel menuModel = value as MenuModel;
if (parameter != null)
{
CollectionContainer collectionContainer = new CollectionContainer();
collectionContainer.Collection = menuModel.Children;
CompositeCollection compositeCollection = new CompositeCollection();
compositeCollection.Add(collectionContainer);
collectionContainer = new CollectionContainer();
collectionContainer.Collection = (IEnumerable)App.Current.MainWindow.FindResource(parameter);
compositeCollection.Add(collectionContainer);
return compositeCollection;
}
else
{
return menuModel.Children;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
As you can see it uses its parameter to get a specific resource (in our case I am using the resource called "someOtherMenus", which is an IEnumerable of MenuModels).
Of course the HierarchicalDataTemplate is recursive so the "someOtherMenus" MenuModels will be added to each level (but the first one) of your Menu.
I hope my sample can help you.

EmptyTextValidationRule not behave as requested

Requirements: We have TextBox and when it is empty and loses focus, textbox will mark itself as "need to be filled" and raise popup.
Implementation: So far i became with following solution:
EmptyTextValidationRule actually check if textbox is empty and raise ValidationResult.
TextBox's style in XAML which responsible to to UI job (i.e. mark red color around textbox and raise popup.
Important NOTE: i cannot afford usage of code behind since this should be generic for ant textbox.
The problem is that my code is not working when textbox is empty and looses its focus.
<Window.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel>
<Grid DockPanel.Dock="Right" Width="16" Height="16" VerticalAlignment="Center" Margin="3 0 0 0">
<Ellipse Width="16" Height="16" Fill="Red" />
<Ellipse Width="3" Height="8" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0 2 0 0" Fill="White" />
<Ellipse Width="2" Height="2" VerticalAlignment="Bottom" HorizontalAlignment="Center" Margin="0 0 0 2" Fill="White" />
</Grid>
<Border BorderBrush="Red" BorderThickness="2" CornerRadius="2">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox Height="20" Width="100" />
<TextBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Left" MinWidth="150" MaxWidth="180" Margin="5,0">
<TextBox.Text>
<Binding Path="IncidentName" Mode="TwoWay" NotifyOnSourceUpdated="True" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<validators:EmptyTextValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
EmptyTextValidationRule:
public class EmptyTextValidationRule : ValidationRule
{
private string m_errorText;
private const string TEXT_REQUERIED = "Text filed should not be empty";
public EmptyTextValidationRule()
{
}
public string ErrorText
{
get { return m_errorText; }
set
{
m_errorText = value;
}
}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string enterendText = value.ToString();
if (string.IsNullOrEmpty(enterendText))
{
if (string.IsNullOrEmpty(ErrorText))
return new ValidationResult(false, TEXT_REQUERIED);
else
return new ValidationResult(false, ErrorText);
}
return new ValidationResult(true, null);
}
}
This is not an attempt to answer your question, instead just pointing out a mistake in your code:
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string enterendText = value.ToString(); //<< You'll get error here if value is null
if (string.IsNullOrEmpty(enterendText)) //<< No point checking here... too late!
{
if (string.IsNullOrEmpty(ErrorText))
return new ValidationResult(false, TEXT_REQUERIED);
else
return new ValidationResult(false, ErrorText);
}
return new ValidationResult(true, null);
}
Using this code, if value was ever null, then you'd get an error in the first if statement condition... you should do something like this instead:
string enterendText = string.Empty;
if (value == null || (enterendText = value.ToString()).Trim() == string.Empty)
{
...
}

XAML to add header to radio button

So with a lot of looking around I am hoping to make a GroupBox that acts like a Radio button. The header section would act as the bullet. I took some code from this question
Styling a GroupBox
that is how I want it to look. But I want to have it as a Radio button. So I put in this code (mind you I've only been doing WPF for a week or 2 now)
<Style TargetType="{x:Type RadioButton}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RadioButton}">
<BulletDecorator>
<BulletDecorator.Bullet>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border x:Name="SelectedBorder"
Grid.Row="0"
Margin="4"
BorderBrush="Black"
BorderThickness="1"
Background="#25A0DA">
<Label x:Name="SelectedLabel" Foreground="Wheat">
<ContentPresenter Margin="4" />
</Label>
</Border>
<Border>
</Border>
</Grid>
</BulletDecorator.Bullet>
</BulletDecorator>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter TargetName="SelectedBorder" Property="Background" Value="PaleGreen"/>
<Setter TargetName="SelectedLabel"
Property="Foreground"
Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I have a feeling that I can add a label to the second row of my grid, but then I don't know how to access it. I have that template in a test project in the Window.Resources section (I plan on moving it to a resource dictionary in my main project)
the xaml for my window is this
<Grid>
<GroupBox Name="grpDoor" Margin ="8" Grid.Row="0" Grid.Column="0">
<GroupBox.Header>
WPF RadioButton Template
</GroupBox.Header>
<StackPanel Margin ="8">
<RadioButton FontSize="15" Content="Dhaka" Margin="4" IsChecked="False"/>
<RadioButton FontSize="15" Content="Munshiganj" Margin="4" IsChecked="True" />
<RadioButton FontSize="15" Content="Gazipur" Margin="4" IsChecked="False" />
</StackPanel>
</GroupBox>
</Grid>
I then hoping for something like this (not sure how I'd do it yet though)
<Grid>
<GroupBox Name="grpDoor" Margin ="8" Grid.Row="0" Grid.Column="0">
<GroupBox.Header>
WPF RadioButton Template
</GroupBox.Header>
<StackPanel Margin ="8">
<RadioButton FontSize="15"
Content="Dhaka"
Margin="4"
IsChecked="False">
<RadioButton.Description>
This is a description that would show under my Header
</RadioButton.Description>
</RadioButton>
<RadioButton FontSize="15"
Content="Munshiganj"
Margin="4"
IsChecked="True">
<RadioButton.Description>
This is a description that would show under my Header
</RadioButton.Description>
</RadioButton>
<RadioButton FontSize="15"
Content="Gazipur"
Margin="4"
IsChecked="False">
<RadioButton.Description>
This is a description that would show under my Header
</RadioButton.Description>
</RadioButton>
</StackPanel>
</GroupBox>
</Grid>
Based on your clarification, here is a very simple example with a RadioButton that looks like a GroupBox.
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:SimpleViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type local:SimpleOption}">
<RadioButton GroupName="choice" IsChecked="{Binding Path=IsSelected, Mode=TwoWay}">
<RadioButton.Template>
<ControlTemplate TargetType="{x:Type RadioButton}">
<GroupBox x:Name="OptionBox" Header="{Binding Path=DisplayName, Mode=OneWay}">
<TextBlock Text="{Binding Path=Description, Mode=OneWay}"/>
</GroupBox>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected, Mode=OneWay}" Value="True">
<Setter TargetName="OptionBox" Property="Background" Value="Blue"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</RadioButton.Template>
</RadioButton>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Path=Options, Mode=OneWay}"/>
</Grid>
</Window>
public class SimpleViewModel
{
public SimpleViewModel()
{
Options = new ObservableCollection<SimpleOption>();
var _with1 = Options;
_with1.Add(new SimpleOption {
DisplayName = "Dhaka",
Description = "This is a description for Dhaka."
});
_with1.Add(new SimpleOption {
DisplayName = "Munshiganj",
Description = "This is a description for Munshiganj.",
IsSelected = true
});
_with1.Add(new SimpleOption {
DisplayName = "Gazipur",
Description = "This is a description for Gazipur."
});
}
public ObservableCollection<SimpleOption> Options { get; set; }
}
public class SimpleOption : INotifyPropertyChanged
{
public string DisplayName {
get { return _displayName; }
set {
_displayName = value;
NotifyPropertyChanged("DisplayName");
}
}
private string _displayName;
public string Description {
get { return _description; }
set {
_description = value;
NotifyPropertyChanged("Description");
}
}
private string _description;
public bool IsSelected {
get { return _isSelected; }
set {
_isSelected = value;
NotifyPropertyChanged("IsSelected");
}
}
private bool _isSelected;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged;
public delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);
}
I'd do it with a custom attached property. That way, you can bind to it from a ViewModel, or apply it directly in XAML.
First, create a new class in your Style assembly:
public static class RadioButtonExtender
{
public static readonly DependencyProperty DescriptionProperty = DependencyProperty.RegisterAttached(
"Description",
typeof(string),
typeof(RadioButtonExtender),
new FrameworkPropertyMetadata(null));
[AttachedPropertyBrowsableForType(typeof(RadioButton))]
public static string GetDescription(RadioButton obj)
{
return (string)obj.GetValue(DescriptionProperty);
}
public static void SetDescription(RadioButton obj, string value)
{
obj.SetValue(DescriptionProperty, value);
}
}
And your style's Bullet would change so that the label is:
<Label x:Name="SelectedLabel"
Foreground="Wheat"
Content="{Binding (prop:RadioButtonExtender.Description), RelativeSource={RelativeSource TemplatedParent}} />
You could then use it in your final XAML:
<RadioButton FontSize="15"
Content="Dhaka"
Margin="4"
IsChecked="False">
<prop:RadioButtonExtender.Description>
This is a description that would show under my Header
</prop:RadioButtonExtender.Description>
</RadioButton>
As an added bonus, since you're creating the Style in a separate assembly, you can create a custom XAML namespace to make using your property easier.

Toolbar item image change when pressed

I have a toolbar that binds it's ItemsSource to my VM, it's a list of ToolBarItem
public class ToolbarItem : ObservableObject
{
public string ToolTip { get; set; }
public ICommand Command { get; set; }
public BitmapImage Icon { get; set; }
private bool _isPressed;
public bool IsPressed
{
get { return _isPressed; }
set { _isPressed = value; RaisePropertyChanged("IsPressed"); }
}
public ToolbarItem(string tooltip, ICommand command, BitmapImage icon)
{
this.Icon = icon;
this.Command = command;
this.ToolTip = tooltip;
}
}
}
this is my Toolbar item template:
<DataTemplate x:Key="toolBarItemTemplate">
<Button x:Name="toolBarButton"
ToolTip="{Binding Path=ToolTip}"
Command="{Binding Path=Command}"
Cursor="Hand"
Style="{StaticResource toolBarButtonItemStyle}">
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource toolBarButtonItemTemplate}" />
</Button>
</DataTemplate>
<DataTemplate x:Key="toolBarButtonItemTemplate">
<Image Width="16"
Height="16"
Source="{Binding Path=Icon}"
Style="{StaticResource toolBarButtonImageStyle}" />
</DataTemplate>
What I want to do is, when the user clicks on specific toolbar button to change that button behavior, for example, have a border around it.
Assuming you don't want to use it as a ToggleButton, try something like this:
<DataTemplate x:Key="toolBarItemTemplate">
<Button x:Name="toolBarButton"
ToolTip="{Binding Path=ToolTip}"
Command="{Binding Path=Command}"
Cursor="Hand"
Style="{StaticResource toolBarButtonItemStyle}">
<!-- added code starts-->
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="BorderBrush" Value="#FF0000"/>
<Setter Property="Foreground" Value="#00FF00"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
<!-- added code ends-->
<ContentControl Content="{Binding}"
ContentTemplate="{StaticResource toolBarButtonItemTemplate}" />
</Button>
</DataTemplate>
<DataTemplate x:Key="toolBarButtonItemTemplate">
<Image Width="16"
Height="16"
Source="{Binding Path=Icon}"
Style="{StaticResource toolBarButtonImageStyle}" />
</DataTemplate>
the way to do it, is using ItemTemplateSelector and based on the item's type, use a different DataTemplate.
this is done in code

wpf listbox checkbox combination, really stuck

I am trying to link the checkbox and listview together, and then use the binding method to set the path to the object in order to set the check-box IsChecked status in the listbox.
List<Test1> datas = new List<Test1>();
var data = new Test1 {Key = 1, Value = "Hello", IsSelected= true};
datas.Add(data);
data = new Test1 {Key = 2, Value = "Hello2", IsSelected= false};
datas.Add(data);
What I need to happen is that if the checkbox is checked ( IsSelected is true ) then I need to populate with those values and then when I click and unclick the checkbox in the GUI I need it to also select the proper listeview item so I can get to the tag property.
This code below does not set the checkbox IsChecked.
<ListBox ItemsSource="{Binding}" Name="lstSwimLane" Width="225" Height="125" SelectionChanged="lstSwimLane_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}, Path=IsSelected, Mode=TwoWay}"
Checked="CheckBox_Checked"
Unchecked="CheckBox_Unchecked" />
<TextBlock Text="{Binding Path=Value}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
What do I need to change in order to set the check box to the value in the object? I even tried INotifyChange etc...
Here is the object as well.
public class Test1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool _isChecked;
public int Key { get; set; }
public string Value { get; set; }
public bool IsSelected
{
get { return _isChecked; }
set
{
if(_isChecked != value)
{
_isChecked = value;
OnPropertyChanged("IsSelected");
}
}
}
protected void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
I am new to all this wpf, and I am stumped.
Thanks.
Do you need this to work "three-way"? So setting any of the three properties
ListBoxItem.IsSelected
CheckBox.IsChecked
Item1.IsSelected
will affect both of the other properties? Unfortunately, there is no such Binding in WPF so you're gonna have to do a little extra work.
Update
As pointed out by Robert Rossney, a much better solution for this is to bind
ListBoxItem.IsSelected to Item1.IsSelected
CheckBox.IsChecked to ListBoxItem.IsSelected
Updated Xaml
<ListBox ItemsSource="{Binding}"
Name="lstSwimLane"
SelectionMode="Multiple"
Width="225" Height="125" SelectionChanged="lstSwimLane_SelectionChanged">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected"
Value="{Binding Path=IsSelected,
Mode=TwoWay}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Checked="CheckBox_Checked"
Unchecked="CheckBox_Unchecked"
IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
Path=IsSelected}">
</CheckBox>
<TextBlock Text="{Binding Path=Value}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In case anyone is interested, here is the markup for the listbox / combox. It will display horizontal.
Thank you all again for all you help as I greatly appreciated it.
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemsSource="{Binding}"
Name="lstSwimLane"
SelectionMode="Multiple"
Width="auto"
Height="auto"
Background="Transparent"
BorderThickness="0"
SelectionChanged="lstSwimLane_SelectionChanged" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding Path=IsChecked, Mode=TwoWay}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="3,3,3,3">
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}"
Checked="CheckBox_Checked"
Unchecked="CheckBox_Unchecked"
VerticalAlignment="Center"
Margin="0,0,4,0" />
<TextBlock Text="{Binding Value}" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Resources