Мне нужно связать "CommonViewModel" объект из кода с помощью "MainWindow" и его потомков "UserControl1" и "UserControl2" в режиме twoways
"CommonViewModel"
"MainWindow"
"UserControl1"
"UserControl2"
MainWindow.xaml
<Window x:Class="Testing.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Testing" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <StackPanel> <local:UserControl1/> <local:UserControl2/> </StackPanel> </Window>
MainWindow.xaml.cs
public partial class MainWindow : Window { public CommonViewModel commonViewModel = new CommonViewModel(); public MainWindow() { InitializeComponent(); this.DataContext = commonViewModel; } }
UserControl1.xaml
<UserControl x:Class="Testing.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <StackPanel > <TextBox Text="{Binding CommonProperity1,Mode=TwoWay}"/> </StackPanel> </UserControl>
UserControl2.xaml
<UserControl x:Class="Testing.UserControl2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <StackPanel> <TextBox Text="{Binding CommonProperity2,Mode=TwoWay}"/> </StackPanel> </UserControl>
Мой объект CommonViewModel.cs
public class CommonViewModel : NotifyChangeClass { private string _Localtextdata1; private string _Localtextdata2; public string CommonProperity1 { get { return _Localtextdata1; } set { _Localtextdata1 = value; NotifyPropertyChange("CommonProperity1"); } } public string CommonProperity2 { get { return _Localtextdata2; } set { _Localtextdata2 = value; NotifyPropertyChange("CommonProperity2"); } } } public class NotifyChangeClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChange(string ProperityName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(ProperityName)); } } }
К сожалению, да, вы правы, это работает, ошибка была в рамках, ничего плохого в коде.
В любом случае, спасибо за попытку помочь.