gpt4 book ai didi

wpf - 依赖 属性依赖于另一个

转载 作者:行者123 更新时间:2023-12-04 19:53:48 27 4
gpt4 key购买 nike

如何注册一个依赖属性,其值是使用另一个依赖属性的值计算的?

由于 .NET 属性包装器在运行时被 WPF 绕过,因此不应在 getter 和 setter 中包含逻辑。解决方案通常是使用 PropertyChangedCallback s。但那些被声明为静态的。

例如,完成这个人为任务的正确方法是什么:

public bool TestBool
{
get { return (bool)GetValue(TestBoolProperty); }
set
{
SetValue(TestBoolProperty, value);
TestDouble = ((value)?(100.0):(200.0)); // HERE IS THE DEPENDENCY
}
}
public static readonly DependencyProperty TestBoolProperty =
DependencyProperty.Register("TestBool", typeof(bool), typeof(ViewModel));

public double TestDouble
{
get { return ((double)GetValue(TestDoubleProperty)); }
set { SetValue(TestDoubleProperty, value); }
}
public static readonly DependencyProperty TestDoubleProperty =
DependencyProperty.Register("TestDouble", typeof(double), typeof(ViewModel));

只要依赖不是循环的,是否有适当的方法来实现这一点?

最佳答案

嗯...我觉得你最好看看依赖属性 value coercion .这是强制转换的示例:

public class ViewModel : DependencyObject
{
public bool TestBool
{
get { return (bool)GetValue(TestBoolProperty); }
set { SetValue(TestBoolProperty, value); }
}
public static readonly DependencyProperty TestBoolProperty =
DependencyProperty.Register("TestBool", typeof(bool), typeof(ViewModel), new PropertyMetadata(false, OnTestBoolPropertyChanged));

private static void OnTestBoolPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var vm = (ViewModel)d;
vm.CoerceValue(TestDoubleProperty);
}

public double TestDouble
{
get { return ((double)GetValue(TestDoubleProperty)); }
set { SetValue(TestDoubleProperty, value); }
}
public static readonly DependencyProperty TestDoubleProperty =
DependencyProperty.Register("TestDouble", typeof(double), typeof(ViewModel), new PropertyMetadata(0.0, null, OnCoerceTestDouble));

private static object OnCoerceTestDouble(DependencyObject d, object baseValue)
{
var vm = (ViewModel) d;
var testBool = vm.TestBool;
return ((testBool) ? (100.0) : (200.0));
}
}

关于wpf - 依赖 属性依赖于另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1364484/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com