2009-09-04 133 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;