gpt4 book ai didi

wpf - DependencyProperty 值未通过数据绑定(bind)设置

转载 作者:行者123 更新时间:2023-12-01 01:36:03 24 4
gpt4 key购买 nike

我有一门课有 DependencyProperty成员:

public class SomeClass : FrameworkElement
{
public static readonly DependencyProperty SomeValueProperty
= DependencyProperty.Register(
"SomeValue",
typeof(int),
typeof(SomeClass));
new PropertyMetadata(
new PropertyChangedCallback(OnSomeValuePropertyChanged)));

public int SomeValue
{
get { return (int)GetValue(SomeValueProperty); }
set { SetValue(SomeValueProperty, value); }
}

public int GetSomeValue()
{
// This is just a contrived example.
// this.SomeValue always returns the default value for some reason,
// not the current binding source value
return this.SomeValue;
}

private static void OnSomeValuePropertyChanged(
DependencyObject target, DependencyPropertyChangedEventArgs e)
{
// This method is supposed to be called when the SomeValue property
// changes, but for some reason it is not
}
}

该属性绑定(bind)在 XAML 中:
<local:SomeClass SomeValue="{Binding Path=SomeBinding, Mode=TwoWay}" />

我正在使用 MVVM,所以我的 View 模型是 DataContext对于这个 XAML。绑定(bind)源属性如下所示:
public int SomeBinding
{
get { return this.mSomeBinding; }
set
{
this.mSomeBinding = value;
OnPropertyChanged(new PropertyChangedEventArgs("SomeBinding"));
}
}

protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = this.PropertyChanged;

if (handler != null)
{
handler(this, e);
}

return;
}

当我访问 this.SomeValue 时,我没有得到绑定(bind)源的值.我究竟做错了什么?

最佳答案

不幸的是,问题不在我分享的任何代码中。原来我的SomeClass实例,我在我的 UserControl 中声明为资源, 没有使用相同的 DataContext作为 UserControl .我有这个:

<UserControl.Resources>
<local:SomeClass x:Key="SomeClass" SomeValue="{Binding Path=SomeBinding, Mode=TwoWay}" />
</UserControl.Resources>

由于 SomeClass对象没有权限 DataContext ,未设置 DependencyProperty...

关于wpf - DependencyProperty 值未通过数据绑定(bind)设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073170/

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