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