WPF:将属性绑定(bind)到自定义 UserControl

标签 wpf validation binding

我在 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/

相关文章:

android - 从另一个应用程序绑定(bind)到服务

MVVM 绑定(bind)密码

c# - WPF 创建滑出面板

WPF:如何使空的 TextBlock 不占用空间?

c# - WPF 列表框布局 : multiple columns

javascript - 使用 Javascript 输入字段需要 8 位数字

.net - 带验证的文本框。即使输入的文本无效,如何更新目标属性?

使用 scanf 询问输入时产生无限循环的代码

ajax - yii ajax表单验证,基于某个字段需要更多字段

java - 无法使用绑定(bind)从 xsd 生成 java 类