我在 wpf 中遇到以下问题:
我已经定义了一个用户控件(在命名空间测试中),其中包含一个文本框(和其他几个控件,只显示 xaml 的相关部分):
<UserControl (...)
DataContext="{Binding RelativeSource={RelativeSource Self}}"
name="Spinbox">
(...)
<StackPanel Orientation="Horizontal">
<TextBox x:Name="tbText" (...)>
<TextBox.Text>
<Binding Path="Value" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:ValidateValue MinVal="0" MaxVal="1" />
</Binding.ValidationRules>
<Binding.NotifyOnValidationError>true</Binding.NotifyOnValidationError>
</Binding>
</TextBox.Text>
</TextBox>
(...)
在主窗口文件中,我使用了这个旋转框:
<Test:SpinBox x:Name="tbTestSpinbox" Value="{Binding Path=TheValue}"
MinValue="0" MaxValue="150">
<Test:SpinBox.Behavior>
<Controls:SpinBoxNormalBehavior />
</Test:SpinBox.Behavior>
</Test:SpinBox>
在后面的代码中,我定义了 TheValue:
private double theValue;
public Window1()
{
InitializeComponent();
TheValue = 10;
}
public double TheValue
{
get { return theValue; }
set
{
theValue = value;
NotifyPropertyChanged("TheValue");
}
}
/// <summary>
/// Occurs when a property value changes
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
当我尝试运行此应用程序时,我在输出窗口中收到消息:
System.Windows.Data Error: 39 : BindingExpression path error: 'TheValue' property not found on 'object' ''SpinBox' (Name='tbTestSpinbox')'. BindingExpression:Path=TheValue; DataItem='SpinBox' (Name='tbTestSpinbox'); target element is 'SpinBox' (Name='tbTestSpinbox'); target property is 'Value' (type 'Double')
并且spinbox填充的不是数值10,而是默认的0。
有谁知道如何确保正确显示该值?
最佳答案
您在其 XAML 中将 UserControl 的 DataContext 设置为其自身:
<UserControl (...)
DataContext="{Binding RelativeSource={RelativeSource Self}}"
...所以稍后当你这样说时:
<Test:SpinBox x:Name="tbTestSpinbox" Value="{Binding Path=TheValue}"
MinValue="0" MaxValue="150">
“值”绑定(bind)正在寻找 SpinBox 本身的“TheValue”属性。
不使用 DataContext,而是更改 UserControl 内的绑定(bind)以绑定(bind)回控件本身。我通常通过为整个 UserControl 指定一个 XAML 名称来做到这一点:
<UserControl x:Name="me">
然后使用元素绑定(bind):
<TextBox.Text>
<Binding Path="Value"
ElementName="me"
UpdateSourceTrigger="PropertyChanged">
关于WPF:将属性绑定(bind)到自定义 UserControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1378003/