I have a MainWindow. It contains an instance of UserControl1 with a TextBox. MainWindow also contains an instance of a Settings class. I would like to bind the TextBox to a string property of the Settings class.
The difficulty is UserControl1 has no knowledge of MainWindow or Settings (since I want to use UserControl1 in multiple projects). So I made an interface IString, and I pass that to UserControl1. However, I still can't get any binding to work. I realize I'll have to add INotifyPropertyChanged at some point, but I don't think that's what's preventing it from working here.
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>
and codebehind:
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>
and codebehind:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public IString Settings { get; set; }
}