我有一个场景,我想根据数据模型中的几个条件在 DockPanel/TextBlock 上为拖放数据添加鼠标和键盘事件。如果该条件不存在,那么我不希望我的代码监听这些事件。
<!-- Data Template with all event handlers -->
<DataTemplate DataType="{x:Type ViewModels:EventsViewModel}">
<DockPanel Name="dpnMain">
<Button Name="btnSourceLink" DockPanel.Dock="Right" HorizontalAlignment="Right" Padding="0"
ClickMode="Press"
Click="Button_OnMouseButtonUp"
PreviewMouseDown="Button_DragDataMouseDown"
Content="{Binding Value, Converter={StaticResource RegionalDataFormatConverter}}"
ToolTip="{Binding Tooltip}"
ToolTipService.IsEnabled="{Binding IsTooltipAvailable}" />
<StackPanel Name="spnWithDragNDrop" DockPanel.Dock="Left">
<TextBlock HorizontalAlignment="Left" TextWrapping="NoWrap" ClipToBounds="True" Padding="0"
Text="{Binding Label}" MouseEnter="OnMouseEnter" MouseLeave="OnMouseLeave"
MouseLeftButtonUp="OnMouseLeftButtonUp"
PreviewMouseDown="DragDataMouseDown"
ToolTip="{Binding Label}"
Width="{Binding ElementName=spn, Path=ActualWidth, Mode=OneWay,
Converter={StaticResource WidthFromParent}, ConverterParameter=10}"/>
</StackPanel>
</DockPanel>
<DataTemplate>
<!-- Data Template without event handlers -->
<DataTemplate DataType="{x:Type ViewModels:PlainViewModel}">
<DockPanel Name="dpnMain">
<Button Name="btnSourceLink" DockPanel.Dock="Right" HorizontalAlignment="Right" Padding="0"
ClickMode="Press"
Click="Button_OnMouseButtonUp"
PreviewMouseDown="Button_DragDataMouseDown"
Content="{Binding Value, Converter={StaticResource RegionalDataFormatConverter}}"
ToolTip="{Binding Tooltip}"
ToolTipService.IsEnabled="{Binding IsTooltipAvailable}" />
<StackPanel Name="spnWithoutDragNDrop" DockPanel.Dock="Left">
<TextBlock HorizontalAlignment="Left" TextWrapping="NoWrap" ClipToBounds="True" Padding="0"
Text="{Binding Label}"
ToolTip="{Binding Label}"
Width="{Binding ElementName=spn, Path=ActualWidth, Mode=OneWay,
Converter={StaticResource WidthFromParent}, ConverterParameter=10}"/>
</StackPanel>
</DockPanel>
<DataTemplate>
<!-- Content Control will select the appropriate data template based on the view model it is bound to -->
<ContentControl Focusable="False" Padding="0" Content="{Binding}"/>
我不想编写两个不同的数据模板,并想根据它的 viewModel 类型进行选择。我需要某种可以绑定到这些事件的 ValueConverters。
无论如何我可以编写一些转换器来避免编写另一个 DataTemplates 和 View Model 并且转换器会在幕后调查这些情况?