2011-05-06 43 views
1

我有一個用戶控件,我想重用,但我似乎無法找到如何更改按鈕的內容的方式。我已經嘗試了我在這裏搜索過的所有東西。如果有人能告訴我缺少什麼,我會非常感激,因爲我一直試圖弄清楚這一點。這裏是我的代碼:用戶控件與按鈕內容綁定

<UserControl x:Class="SamplePopupWPF.UserControl1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Height="300" Width="300"> 
<Grid> 
    <StackPanel> 
     <Button x:Uid="btnLeft" Name="btnBindCmd" Height="23" Click="AddCommand" Content="{Binding ContentText, Mode=TwoWay}", DataContext="UserControl1"/> 

    </StackPanel> 
</Grid> 

代碼的用戶控制:

public string ContentText 
    { 
     get { return (string) GetValue(ContentTextProperty); } 
     set { SetValue(ContentTextProperty, value); } 
    } 

    public static readonly DependencyProperty ContentTextProperty = DependencyProperty.Register("ContentText",  typeof (String), typeof (UserControl1),new IPropertyMetadata(String.Empty,textChangedCallback)); 

    static void textChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 

     UserControl1 c = (UserControl1) d; 
     c.ContentText = e.NewValue as String; 
    } 

下面是使用控制SomePage的:」

<Grid > 
      <user:UserControl1 x:Name="btnTEST" AddCommandClick="onBtnClick" ContentText="{Binding OtherCmd, ElementName=UserControl1}" /> 

    </Grid> 

代碼SomePage的使用控制:

public string OtherCmd 
    { 

     get { return _otherCmd; } 
     set 
     { 
      _otherCmd = value; 
      //if (this.PropertyChanged != null) 
       NotifyProperty("OtherCmd"); 

     } 
    } 

private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
      OtherCmd = "helloTest"; 
    } 

public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyProperty(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

在某些時候,我還沒有使用我放在上面的所有代碼,但仍然無法工作。請幫忙。謝謝。

回答

1

該按鈕綁定到ContentText但沒有DataContext,所以它從它的父級繼承它。你可能想這樣做:

<UserControl 
     x:Name="root" 
     x:Class="SamplePopupWPF.UserControl1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Height="300" 
     Width="300"> 
    <Grid DataContext="{Binding ElementName=root}"> 
     <StackPanel> 
      <Button x:Uid="btnLeft" Name="btnBindCmd" Height="23" Click="AddCommand" Content="{Binding ContentText, Mode=TwoWay}", DataContext="UserControl1"/> 
     </StackPanel> 
    </Grid> 
</UserControl> 

注根GridDataContext集到UserControl本身。因此,Button中的Binding將嘗試解析UserControl實例上的ContentText屬性。

1

在您的UserControl1.xaml.cs中編寫this.DataContext = this;下的InitializeComponent();的構造函數。

這是因爲您無法像在UserControl1.xaml中那樣指定datacontext。肯特展示了正確的方法。

+0

我嘗試了上述建議,但它不工作:(。另外,請注意,我的樣本中,使用用戶控件的一個是SomePage的。 xaml,並且按鈕內容文本將來自Somepage.cs代碼。請任何其他建議?謝謝你! – user742102 2011-05-08 06:26:24

1

你只需要繼承與INotifyPropertyChanged的您SomePage的這樣

public class Subject :INotifyPropertyChanged 
{ 

}