简体   繁体   中英

Share dependency property between usercontrol

I'm trying to build an MVVM application without using any MVVM framework. I've defined my main window and viewmodel, an appcontroller, a couple of views (UserControl as generally adviced) that are displayed in a mainwindow panel, sharing the same look&feel by using composition with another usercontrol which contains common style , so far so good.

My problem is : I would like that all my views "objects" share a couple of dependency properties (view title, help context , etc ...).

The problem is : you cannot put the same DP name to several objects, you can not modify in design mode something that inherits from usercontrol (VS designer seems to only recognize Window, UserControl and Page objects)

I think that I miss something here but cannot put the finger on it. Can you help me ?

Finally got through it.

  • Declare a control inheriting from usercontrol (cs file only, no xaml)

     public class BaseView : UserControl { public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } // Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc... public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(BaseView), new PropertyMetadata("New view")); public BaseView() { } } 
  • Declare a style in global resources for this control :

     <Style TargetType="{x:Type views:BaseView}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type views:BaseView}"> <Border CornerRadius="5" BorderThickness="2"> <Grid Name="RootGrid"> <ContentPresenter></ContentPresenter> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> 
  • After you can subclass your BaseView control in another control :

     <local:BaseView x:Class="MyNS.NiceView" 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" Title="My Software" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <StackPanel> <Button>HAAAAhahahaha</Button> <Label>213456789</Label> </StackPanel> </Grid> </local:BaseView> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM