Hallo,
ich suche nach einem Weg wie man die CheckBox die in einem ListBoxItem bzw. dem Template steckt, mit einem Doppelklick automatisch auf "isChecked" setzen könnte.
Wie könnte man das lösen, gibt es eine reien XAML-Lösung dafür?
Eine reine XAML Lösung kann ich dir dazu nicht bieten aber hier ein Ansatz, wie ich es mit einem im MVVM umsetzen würde:
Du erstellst ein Attached Dependency Property wie folgt oder so ähnlich:
public class ListBoxDoubleClickBehavior
{
private readonly ListBoxItem _item;
private readonly ICommand _command;
private ListBoxDoubleClickBehavior(ListBoxItem item, ICommand command)
{
_item = item;
_command = command;
_item.Loaded += ItemLoaded;
_item.Unloaded += ItemUnloaded;
}
private void ItemLoaded(object sender, RoutedEventArgs e)
{
_item.MouseDoubleClick += ItemMouseDoubleClick;
}
private void ItemUnloaded(object sender, RoutedEventArgs e)
{
_item.MouseDoubleClick -= ItemMouseDoubleClick;
}
private void ItemMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (_command.CanExecute(_item.DataContext))
_command.Execute(_item.DataContext);
}
public static readonly DependencyProperty DoubleClickCommandProperty =
DependencyProperty.RegisterAttached("DoubleClickCommand", typeof(ICommand), typeof(ListBoxDoubleClickBehavior),
new FrameworkPropertyMetadata(default(ICommand), DoubleClickPropertyChangedCallback));
private static void DoubleClickPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
new ListBoxDoubleClickBehavior((ListBoxItem)d, e.NewValue as ICommand);
}
public static void SetDoubleClickCommand(UIElement element, ICommand value)
{
element.SetValue(DoubleClickCommandProperty, value);
}
public static ICommand GetDoubleClickCommand(UIElement element)
{
return (ICommand)element.GetValue(DoubleClickCommandProperty);
}
}
im XAML fügst du das Property dann per Style ans ListboxItem an:
<ListBox ItemsSource="{Binding Path=Items}">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="YourNameSpace:ListBoxDoubleClickBehavior.DoubleClickCommand"
Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}},
Path=DataContext.YourViewModelDoubleClickCommand}"/>
</Style>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<CheckBox IsChecked="{Binding Path=IsMyCheckBoxChecked}"/>
<TextBlock Text="{Binding Path=NameOfMyListBoxItem}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Und in deinem ViewModel kannst du dann im Command ganz bequem tun und lassen was du willst wie zum Beispiel das ViewModel deines ListBoxItems manipulieren:
YourViewModelDoubleClickCommand = new DelegateCommand(item =>
item.IsMyCheckBoxChecked = !item.IsMyCheckBoxChecked);
Lg und viel Spaß beim Werken,
XXX