我有一个用户控件,我想重用,但我似乎无法找到如何更改按钮的内容的方式。我已经尝试了我在这里搜索过的所有东西。如果有人能告诉我缺少什么,我会非常感激,因为我一直试图弄清楚这一点。这里是我的代码:用户控件与按钮内容绑定
<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));
}
}
在某些时候,我还没有使用我放在上面的所有代码,但仍然无法工作。请帮忙。谢谢。
我尝试了上述建议,但它不工作:(。另外,请注意,我的样本中,使用用户控件的一个是SomePage的。 xaml,并且按钮内容文本将来自Somepage.cs代码。请任何其他建议?谢谢你! – user742102 2011-05-08 06:26:24