Currently, I have a working C# WPF application consisting of several User Controls. One of the User Controls needs data from this MainWindow to properly display additional information and process itself. (For now, it would be satisfactory just to pass a string between the MainWindow and the User Control.) I already am able via a Dependency Property (in the UC code behind) to bind the data to the User Control XAML, and it displays fine. However, I am unable to access that same data (that is being displayed in the view model that is tied to the UC.
Here are related code snippets:
MainWindow XAML:
<UCV:SetupUC UC1="{Binding DataContext.ContainerData, ElementName=winCon, Mode=TwoWay}">
</UCV:SetupUC>
SetupUC XAML (this is the User Control):
<TextBox x:Name="tbx1" HorizontalAlignment="Left" Height="23" Margin="159,22,0,0" TextWrapping="Wrap" Text="{Binding UC1, ElementName=root}" VerticalAlignment="Top" Width="120"/>
Note, this is displaying fine, including changing as the value changes in the MainWindow.
SetupUC Code behind:
public partial class SetupUC : UserControl, INotifyPropertyChanged
{
public static readonly DependencyProperty UC1Property = DependencyProperty.Register("UC1", typeof(string),
typeof(SetupUC), new PropertyMetadata(OnUC1Changed));
public string UC1
{
get { return (string)GetValue(UC1Property); }
set
{
SetValue(UC1Property, value);
}
}
public SetupUC()
{
InitializeComponent();
SetupViewModel svm = new SetupViewModel(UC1);
this.DataContext = svm;
}
}
Finally, SetupViewModel:
public class SetupViewModel : INotifyPropertyChanged
{
public SetupViewModel(string UC2)
{
ContainerData = UC2;
_UserProfile = new UserProfile();
UserProfile.Pwd = ContainerData;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _containerData;
public string ContainerData
{
get { return _containerData; }
set
{
_containerData = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("ContainerData"));
}
}
}
}
UC1 in the code behind which does display in the SetupUC view, never seems to pass to the view model, UC2. Interestingly enough, if I replace the UC1 in the code behind with a string like "123" it will get passed to the VM in UC2.
I am pretty new to C# and MVVM, and I have been googling this for days. Found a lot of posts and have trid different recs. from those posts, but still no luck...
Help, please?!?