I have a custom control, which has a button:
If you do not want to define a property in the UserControl
, which you can always create attached dependency property, and you can declare it in a separate class under the common namespace.
Something like this:
MainWindow.xaml
TestUserControl.xaml
Attached property definition:
public static class ButtonExt
{
public static readonly DependencyProperty VisibilityProperty;
public static void SetVisibility(DependencyObject DepObject, Visibility value)
{
DepObject.SetValue(VisibilityProperty, value);
}
public static Visibility GetVisibility(DependencyObject DepObject)
{
return (Visibility)DepObject.GetValue(VisibilityProperty);
}
static ButtonExt()
{
PropertyMetadata VisibiltyPropertyMetadata = new PropertyMetadata(Visibility.Collapsed);
VisibilityProperty = DependencyProperty.RegisterAttached("Visibility",
typeof(Visibility),
typeof(ButtonExt),
VisibiltyPropertyMetadata);
}
}
Some notes about code-behind in MVVM
I agree with @dkozl, his example does not violate the principle of MVVM, in some cases, the code is present in the View
, for example (personally, I always try to avoid code-behind):
Installation DataContext
.
The use of different patterns such as Mediator, Proxy, etc.
Determination of properties and behaviors that pertain only to View
(as in your case).
The most important thing when you use the code-behind, it is that all actions possible through ViewModel
occurred, ie in ViewModel
contains all the logic and for example, in the View
click event, call the function, which is in ViewModel
.
For more information about code-behind, please see the answers to the recent question:
WPF MVVM Code Behind