我正在努力使现有的风格更加灵活。 我正在附上一个dep。属性到数据网格行控件的双击事件。 在双击该行时,我想要打开某个窗口。 为了达到这个目的,我实现了一个dep。属性并添加了样式定义。 以下是视图文件中的部分:
<Style x:Key="SomeKey" TargetType={x:Type DataGridRow} BasedOn= "SomeOtherKey">
<Setter Property="vm:DataGridBehavior:OnDoubleClick" Value="{Binding Path=CommandName,
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}">
</Setter>
</Style>
附加属性挂钩到数据行上的双击事件 并执行绑定到视图的relay命令。 我想在风格上增加灵活性 通过在视图本身中指定要调用的命令名称(因为它可能在不同视图之间有所不同)。 我怎样才能做到这一点? 我缺少任何模板定义吗? 任何帮助将不胜感激:)
答案 0 :(得分:2)
您可以继承DataGrid
并为命令添加属性,例如MyCommand。然后你可以在每个DataGrid
中绑定该ICommand,并在RowStyle绑定中使用MyCommand作为Path
<强>的DataGrid 强>
<local:CommandDataGrid RowStyle="{StaticResource SomeKey}"
MyCommand="{Binding CommandName1}">
<!-- ... -->
<local:CommandDataGrid RowStyle="{StaticResource SomeKey}"
MyCommand="{Binding CommandName2}">
<强> RowStyle 强>
<Style x:Key="SomeKey" TargetType="{x:Type DataGridRow}">
<Setter Property="vm:DataGridBehavior.OnDoubleClick"
Value="{Binding Path=MyCommand,
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
</Style>
<强> CommandDataGrid 强>
public class CommandDataGrid : DataGrid
{
public static readonly DependencyProperty MyCommandProperty =
DependencyProperty.Register("MyCommand",
typeof(ICommand),
typeof(CommandDataGrid),
new UIPropertyMetadata(null));
public ICommand MyCommand
{
get { return (ICommand)GetValue(MyCommandProperty); }
set { SetValue(MyCommandProperty, value); }
}
}
或者,您可以创建附加属性,例如您使用的MyCommand
DataGrid
<DataGrid vm:DataGridBehavior.MyCommand="{Binding CommandName}"
RowStyle
<Style x:Key="SomeKey" TargetType="{x:Type DataGridRow}">
<Setter Property="vm:DataGridBehavior.OnDoubleClick"
Value="{Binding Path=(vm:DataGridBehavior.MyCommand),
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
</Style>
<强> MyCommandProperty 强>
public static readonly DependencyProperty MyCommandProperty =
DependencyProperty.RegisterAttached("MyCommand",
typeof(ICommand),
typeof(DataGridBehavior),
new UIPropertyMetadata(null));
public static void SetMyCommand(DependencyObject element, ICommand value)
{
element.SetValue(MyCommandProperty, value);
}
public static ICommand GetMyCommand(DependencyObject element)
{
return (ICommand)element.GetValue(MyCommandProperty);
}