I have extended ListView class and created two DataTemplate
for it in the separate Resource file. My question is how I can add event handlers for the Checkbox
(and other items) in the DataTemplate
?
MyListView.cs
using System.Windows;
using System.Windows.Controls;
namespace WpfCustomControlLibrary1
{
public class MyListView : ListView
{
public enum ListMode
{
List, ListCheck
}
public static readonly DependencyProperty ModeProperty = DependencyProperty.Register
(
"Mode",
typeof(ListMode),
typeof(MyListView),
new PropertyMetadata(ListMode.List)
);
public ListMode Mode
{
get { return (ListMode)GetValue(ModeProperty); }
set { SetValue(ModeProperty, value); }
}
}
}
MyListViewItem.cs
using System.Windows;
using System.Windows.Controls;
namespace WpfCustomControlLibrary1
{
public class MyListViewItem:Control
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register
(
"Text",
typeof(string),
typeof(MyListViewItem),
new UIPropertyMetadata(string.Empty)
);
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register
(
"IsChecked",
typeof(bool),
typeof(MyListViewItem),
new UIPropertyMetadata(false)
);
public bool IsChecked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
}
}
ResourceDictionary.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary1">
<DataTemplate x:Key="ItemTemplate_List">
<TextBlock Text="{Binding Text}" HorizontalAlignment="Left"/>
</DataTemplate>
<DataTemplate x:Key="ItemTemplate_ListCheck">
<Grid>
<CheckBox IsChecked="{Binding IsChecked}"/>
<TextBlock Text="{Binding Text}" Margin="20,0,0,0" HorizontalAlignment="Left"/>
</Grid>
</DataTemplate>
<Style TargetType="{x:Type local:MyListView}">
<Style.Triggers>
<Trigger Property="Mode" Value="List">
<Setter Property="ItemTemplate" Value="{StaticResource ItemTemplate_List}"/>
</Trigger>
<Trigger Property="Mode" Value="ListCheck">
<Setter Property="ItemTemplate" Value="{StaticResource ItemTemplate_ListCheck}"/>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>