UserControl.xaml:
UserControl.xaml.cs:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string Item
{
get { return (string)GetValue(ItemProperty);}
set { SetValue(ItemProperty,value);}
}
public static readonly DependencyProperty ItemProperty=
DependencyProperty.Register("Item",typeof(string),typeof(UserControl1),new PropertyMetadata("Unspecified"));
}
MainWindow.xaml:
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
UserControl1 uc =null;
ViewModel vm=new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext=vm;
}
private void add_Click(object sender, RoutedEventArgs e)
{
uc = new UserControl1();
uc.Item=vm.MyItem;
panel.Children.Add(uc);
}
}
public class ViewModel:INotifyPropertyChanged
{
private string myItem;
public string MyItem
{
get { return myItem; }
set
{
myItem = value;
OnPropertyChanged("MyItem");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}