2011-05-06 47 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 
{ 

}