Wpf 如何创建/使用在读取时生成其值的DependencyProperty?
我想创建一个可以在每次读取时生成值的;e、 g.类似于:Wpf 如何创建/使用在读取时生成其值的DependencyProperty?,wpf,generator,dependency-properties,Wpf,Generator,Dependency Properties,我想创建一个可以在每次读取时生成值的;e、 g.类似于: private static Random _rng = new Random(); public int RandomNumber { get { int x = _rng.Next(); SetValue(RandomNumberProperty, x); return x; } } private static readonly DependencyPrope
private static Random _rng = new Random();
public int RandomNumber
{
get
{
int x = _rng.Next();
SetValue(RandomNumberProperty, x);
return x;
}
}
private static readonly DependencyPropertyKey RandomNumberProperty = DependencyProperty.RegisterReadOnly(nameof(RandomNumber), typeof(int), typeof(Window1), new PropertyMetadata(-1));
并使用此属性填充;e、 g:
在XAML中:
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:Window1.CmdRandomNumber}"
Executed="ExecuteShowMessage"
CanExecute="CanExecuteShowMessage" />
</CommandBinding>
</Window.CommandBindings>
<Button Command="{x:Static local:Window1:CmdRandomNumber}"
CommandParameter="{Binding RandomNumber}"/>
</Window>
但是,这不起作用:ExecuteShowMessage
始终接收初始值。可能是因为未将值更改通知,并且当请求DependencyProperty
的值时,它返回其缓存值,而不是从RandomNumber
检索它
我想将不同的参数绑定到不同的按钮,并让每个按钮执行相同的命令;因此,我尝试使用,而不是从ExecuteShowMessage
中读取RandomValue
如何实现可在每次读取时生成其值的WPF数据绑定中使用的属性?如何确保它的支持属性被读取,而不是依赖于它的缓存值?(尤其是在以下情况下)
如何实现可在WPF数据绑定中使用的属性
每次读取时生成其值
WPF绑定的源属性可以是普通CLR属性,如下所示:
public int RandomNumber
{
get { return _rng.Next(); }
}
如果需要强制更新绑定以读取新的属性值,则拥有该属性的类可以实现INotifyPropertyChanged
接口,并在必要时触发PropertyChanged
事件,如:
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("RandomNumber"));
依赖项属性不应该以这种方式工作。它的CLR包装器不能调用get和set访问器中的GetValue和SetValue之外的任何东西。但是,如果该属性用作绑定的源,则它不需要是dependency属性。您无法确保总是使用CLR包装来检索dependency属性的值。GetValue和SetValue方法不是虚拟的,因此不能重写它们。不管你想做什么,你都应该考虑另一种方法。对DP的最后一个参数--<代码>新的属性元数据(-1)是默认的。如果您能找到一种方法来返回预先创建的静态随机值,而不是-1,您可能会成功。@LynnCrumbling感谢您的建议,但我希望每次执行命令时随机值都会更改;随机初始值是不够的。
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("RandomNumber"));