M. *_*ley 4 data-binding wpf binding dependency-properties
我有一个班级,其中有一个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
}
}
Run Code Online (Sandbox Code Playgroud)
该属性在 XAML 中绑定:
<local:SomeClass SomeValue="{Binding Path=SomeBinding, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)
我正在使用 MVVM,因此我的视图模型是DataContext
针对此 XAML 的。绑定源属性如下所示:
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;
}
Run Code Online (Sandbox Code Playgroud)
当我访问 时,我没有获得绑定源的值this.SomeValue
。我究竟做错了什么?
不幸的是,问题不在我共享的任何代码中。事实证明,SomeClass
我在 my 中声明为资源的实例UserControl
并没有使用DataContext
与UserControl
. 我有这个:
<UserControl.Resources>
<local:SomeClass x:Key="SomeClass" SomeValue="{Binding Path=SomeBinding, Mode=TwoWay}" />
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)
由于该SomeClass
对象没有 right DataContext
,因此未设置 DependencyProperty...
归档时间: |
|
查看次数: |
7168 次 |
最近记录: |