Wpf 带有按钮内容绑定的usercontrol
我有一个usercontrol,我想重用它,但我似乎找不到一种方法来更改按钮的内容。我已经试过这里所有的东西了。如果有人能告诉我遗漏了什么,我会非常感激,因为我一整天都在努力想办法解决这个问题。这是我的密码:Wpf 带有按钮内容绑定的usercontrol,wpf,user-controls,binding,dependency-properties,Wpf,User Controls,Binding,Dependency Properties,我有一个usercontrol,我想重用它,但我似乎找不到一种方法来更改按钮的内容。我已经试过这里所有的东西了。如果有人能告诉我遗漏了什么,我会非常感激,因为我一整天都在努力想办法解决这个问题。这是我的密码: <UserControl x:Class="SamplePopupWPF.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schem
<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>
以下是使用控件的Somepage:“
在某些情况下,我没有使用上面放置的所有代码,但仍然无法工作。请提供帮助。谢谢。该按钮绑定到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>
注意,根
网格
将其数据上下文
设置为用户控件
本身。因此,按钮
中的绑定
将尝试解析用户控件
实例上的内容文本
属性。在UserControl1.xaml.cs writethis.DataContext=this;
>在构造函数中的InitializeComponent();
下
这是因为您无法按照在UserControl1.xaml中的方式分配datacontext。Kent显示了正确的方式。您只需继承您的somepage,并将inotifyProperty更改为这样
public class Subject :INotifyPropertyChanged
{
}
我尝试了上面的建议,但它不起作用:(。另外,请注意,在我的示例中,使用usercontrol的是Somepage.xaml,按钮内容文本将来自Somepage.cs代码。是否还有其他建议?谢谢!
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));
}
}
<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>
public class Subject :INotifyPropertyChanged
{
}