我有一个MainWindow。它包含带文本框的UserControl1实例。 MainWindow还包含一个Settings类的实例。我想将TextBox绑定到Settings类的字符串属性。
困难在于UserControl1不了解MainWindow或设置(因为我想在多个项目中使用UserControl1)。因此,我创建了一个接口IString,并将其传递给UserControl1。但是,我仍然无法获得任何约束。我意识到我必须在某个时候添加INotifyPropertyChanged,但是我认为这并不能阻止它在这里工作。
public interface IString
{
string String { get; set; }
}
public class Settings : IString
{
public string String { get; set; }
}
MainWindow XAML:
<Window x:Class="WpfApp1.MainWindow">
<local:UserControl1 x:Name="TheUserControl"/>
</Window>
和代码隐藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TheUserControl.Settings = new Settings();
}
}
UserControl1 XAML:
<UserControl x:Class="WpfApp1.UserControl1"
<TextBox DataContext="Settings" Text="{Binding String}"/>
</UserControl>
和代码隐藏:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public IString Settings { get; set; }
}
答案 0 :(得分:1)
您想要做的就是使它UserControl
中的属性可与MainWindow
绑定。为此,将其设置为dependency property。另外,正如@Clemens建议的那样,您可以在属性更改时添加属性chnanged回调以执行其他代码。此外,您还可以设置默认属性并配置其他回叫see here for more info
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public static readonly DependencyProperty SettingsProperty
= DependencyProperty.Register("Settings", typeof(string), typeof(UserControl1),
new PropertyMetadata(
"DefaultSetting",
new PropertyChangedCallback(OnSettingsChanged)));
public string Settings
{
get { return (string)GetValue(SettingsProperty); }
set { SetValue(SettingsProperty, value); }
}
private static void OnSettingsChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (UserControl1)d;
var newSettings = (string)e.NewValue;
//Optionally do something when Settings changed
}
}
然后在MainWindow
<Window x:Class="WpfApp1.MainWindow">
<local:UserControl1 x:Name="TheUserControl" Settings="{Binding xyz}"/>
</Window>