MVVM + UserControl + Dependency Property

Well, this is somewhat related to this question: WPF Printing multiple pages from one view model

I tried to follow the advice given there, but now I'm stuck.

My application uses MainView.xaml and the corresponding MainViewViewModel.cs, I use MVVM Light in the background.

Now - according to the post - it seems I need to do the following:

  • Create custom control
  • Derive some properties from a user control
  • Verify that the view model displays these properties.

The idea is clear, but I'm stuck trying to notify each other.

My user control (UcTest.xaml) provides a dependency property:

public string SpecialText
{
    get { return (string)GetValue(SpecialTextProperty); }
    set
    {
        SetValue(SpecialTextProperty, value);

    }
}

// Using a DependencyProperty as the backing store for SpecialText.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty SpecialTextProperty =
    DependencyProperty.Register("SpecialText", typeof(string), typeof(UcTest), new PropertyMetadata(new PropertyChangedCallback(SpecialTextChangedPropertyCallback)));

private static void SpecialTextChangedPropertyCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    // Do something
    Debug.WriteLine("Ffgdgf");
}

, , . , ViewModel (, ).

, :

  • ViewModel UserControl, ?
  • ?

โ„– 1: () , : . UserControl1 ( ViewModel UserControl1) MainViewViewModel.

+5
2

, Google , "" . , MainViewModel ViewModel UserControl ( ... .. ). , ViewModel.

, .

+4

UserControl ViewModel. : ViewModel View .

<Window x:Class="TestApplication.MainWindow" ...>
    <Window.DataContext>
        <local:MyViewModel/>
    </Window.DataContext>
    <Grid>
        <local:UcTest SpecialText="{Binding MyViewModelProperty, Mode=TwoWay}"/>
    </Grid>
</Window>

ViewModel , UserControl DataContext ViewModel. DataContext MainWindow.

var viewModel = DataContext as MyViewModel;
var property = viewModel.MyViewModelProperty;

, ViewModel UserControl DataContext:

<local:UcTest SpecialText="{Binding MyViewModelProperty, Mode=TwoWay}"/>
    <local:UcTest.DataContext>
        <local:UserControlViewModel/>
    </local:UcTest.DataContext>
</local:UcTest>

ViewModel DataContext

<local:UcTest DataContext="{StaticResource MyUserControlViewModel}"
              SpecialText="{Binding MyViewModelProperty, Mode=TwoWay}"/>
+5

All Articles