【问题标题】:Share dependency property between usercontrol在用户控件之间共享依赖属性
【发布时间】:2017-10-03 08:16:44
【问题描述】:
我正在尝试在不使用任何 MVVM 框架的情况下构建 MVVM 应用程序。
我已经定义了我的主窗口和视图模型、一个应用程序控制器、几个显示在主窗口面板中的视图(通常建议的用户控件),通过与另一个包含通用样式的用户控件使用组合来共享相同的外观和感觉,到目前为止一切都很好.
我的问题是:我希望我的所有视图“对象”共享几个依赖属性(视图标题、帮助上下文等)。
问题是:你不能把同一个 DP 名字放到几个对象上,你不能
在设计模式下修改继承自 usercontrol 的东西(VS 设计器似乎只识别 Window、UserControl 和 Page 对象)
我认为我在这里错过了一些东西,但无法找到它。你能帮帮我吗?
【问题讨论】:
标签:
c#
mvvm
user-controls
dependency-properties
【解决方案1】:
终于熬过去了。
-
声明一个从usercontrol继承的控件(仅cs文件,无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()
{
}
}
-
在全局资源中为此控件声明一个样式:
<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>
-
在您可以将 BaseView 控件子类化到另一个控件中之后:
<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>