2009-09-04 159 views
2

我在WPF以下问题: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') 

而且纺纱器不填充值10,但默认为0

不任何人有一个想法如何确保价值正确显示?

回答

9

你设置用户控件的DataContext的本身在XAML:

<UserControl (...) 
    DataContext="{Binding RelativeSource={RelativeSource Self}}" 

...所以以后当你这样说:

<Test:SpinBox x:Name="tbTestSpinbox" Value="{Binding Path=TheValue}" 
      MinValue="0" MaxValue="150"> 

“值”绑定找SpinBox本身的“TheValue”属性。

而不是使用DataContext,更改您在UserControl内的绑定以绑定回控件本身。我通常做的是通过给整个用户控件一个XAML名称:

<UserControl x:Name="me"> 

,然后使用元素绑定:

<TextBox.Text> 
    <Binding Path="Value" 
      ElementName="me" 
      UpdateSourceTrigger="PropertyChanged"> 
1

除非另有规定,结合路径总是相对于DataContext的。所以在你的窗口的构造函数中,你应该添加该指令:

this.DataContext = this;