带有按钮内容绑定的usercontrol

时间:2011-05-06 16:42:54

标签: wpf user-controls binding dependency-properties

我有一个我想重用的用户控件,但我似乎找不到如何更改按钮内容的方法。我已经尝试过我在这里搜索过的所有内容了。如果有人可以告诉我缺少什么,我会非常感激,因为我一直试图弄清楚这一点。这是我的代码:

    <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));
        }
    }

在某些时候,我没有使用上面放置的所有代码,但仍然无效。请帮忙。感谢。

3 个答案:

答案 0 :(得分: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本身。因此,Binding中的Button会尝试解析ContentText个实例上的UserControl属性。

答案 1 :(得分:1)

在UserControl1.xaml.cs中,在构造函数的this.DataContext = this;下编写InitializeComponent();

这是因为您不能像在UserControl1.xaml中那样分配datacontext。肯特展示了正确的方法。

答案 2 :(得分:1)

您只需要使用INOTIFYPROPERTYCHANGED继承您的某个页面

public class Subject :INotifyPropertyChanged
{

}