C# 具有Freezable StaticResource的DataGrid单元格样式设置器
我想用setter设置WPF数据网格中的按钮命令。但是,在我在中返回一个副本后,DP属性C# 具有Freezable StaticResource的DataGrid单元格样式设置器,c#,wpf,datagrid,C#,Wpf,Datagrid,我想用setter设置WPF数据网格中的按钮命令。但是,在我在中返回一个副本后,DP属性CommandProperty似乎用其默认值null写入 CreateInstanceCore(),因此原始命令将丢失 如果我直接绑定StaticResource,它就会正常工作。 有没有办法阻止这种行为或其他解决方案 public class ResourceCommand : Freezable, ICommand { public ICommand Command { get
CommandProperty
似乎用其默认值null
写入
CreateInstanceCore()
,因此原始命令将丢失
如果我直接绑定StaticResource
,它就会正常工作。
有没有办法阻止这种行为或其他解决方案
public class ResourceCommand : Freezable, ICommand {
public ICommand Command {
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Using a DependencyProperty as the backing store for Command. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(ResourceCommand), new UIPropertyMetadata(null, CommandPropertyChangedCallback));
static void CommandPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) {
ResourceCommand resourceCommand = (ResourceCommand)d;
int h = resourceCommand.GetHashCode();
if (e.OldValue != null)
((ICommand)e.OldValue).CanExecuteChanged -= resourceCommand.OnCanExecuteChanged;
if (e.NewValue != null)
((ICommand)e.NewValue).CanExecuteChanged += resourceCommand.OnCanExecuteChanged;
}
#region ICommand Member
public bool CanExecute(object parameter) {
if (Command == null)
return false;
return Command.CanExecute(parameter);
}
public event EventHandler CanExecuteChanged;
void OnCanExecuteChanged(object sender, EventArgs e) {
if (CanExecuteChanged != null)
CanExecuteChanged(sender, e);
}
public void Execute(object parameter) {
Command.Execute(parameter);
}
#endregion
protected override Freezable CreateInstanceCore() {
ResourceCommand ResourceCommand = new ResourceCommand();
ResourceCommand.Command = Command;
return ResourceCommand;
}
}
xaml:
如果您像下面这样定义资源命令,它会起作用:
<local:ResourceCommand x:Key="FirstCommand" Command="{Binding FirstCommand}" x:Shared="False"/>
使用此技术,您甚至可以在
CreateInstanceCore
中抛出未实现,因此您只需使用Freezable
来启用数据绑定。1。按钮位于DataGrid之外,命令绑定时不使用style:Works。但是以前也工作过。2.DataGrid外部的按钮,使用样式设置器的命令设置:不起作用。调用CreateInstanceCore()。2.按钮,命令绑定时不使用样式或将命令设置为样式:无效。调用CreateInstanceCore()。我测试了1。二,。在DataGrid
中,DataContext
将不同,因此请确保您在那里有一个命令,因为写入的绑定始终与分配给它的元素的数据上下文相关。因此,它将命令绑定到项,而不是窗口的DataContext
?如果是,是否有方法绑定到我的窗口的DataContext
?x:Shared=“false”
不是相反,让它一直克隆吗?您可以像绑定任何其他数据绑定一样绑定到命名元素,例如{binding DataContext.FirstCommand,ElementName=window}
。不可冻结的事物可以使用“x:Shared=“False“
仍会被复制,因为复制未使用Freezable
克隆机制。它从XAML树创建一个新资源。但是DataGrid
的子项不在可视化树中,因此它将无法找到窗口。这就是为什么我尝试使用这种方法来过度绑定静态资源。我希望它能保存对我的窗口的datacontext命令的引用,我可以共享它。直到我尝试将命令设置在样式设置器上,而不是直接绑定。
<local:ResourceCommand x:Key="FirstCommand" Command="{Binding FirstCommand}" x:Shared="False"/>