我在StackPanel中有多个相同自定义用户控件的实例。每个实例都需要相同的DependencyProperty“ControlWidth”。我想在父StackPanel中只设置一次
,而不是使用相同的属性设置每个用户控件 <StackPanel>
<propwin:PropertyEditControl Label="First" ControlWidth="180" />
<propwin:PropertyEditControl Label="First" ControlWidth="180" />
...
</StackPanel>
我曾经使用样式属性
执行此操作 <StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type propwin:PropertyEditControl}">
<Setter Property="ControlWidth" Value="180" />
</Style>
</StackPanel.Resources>
<propwin:PropertyEditControl Label="First" />
<propwin:PropertyEditControl Label="Second" />
...
</StackPanel>
更新: 感谢Anatoliy,他提到我的代码(我在这里展示的代码)应该可行。我现在追查了这个问题。在我的PropertyEditControl.xaml中,我定义了一种验证方式:
<UserControl x:Class="MyModule.PropertyEditControl"
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"
xmlns:local="clr-namespace:MyModule">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyModule;component/UI/ResourceDictionaries/ResourceLibrary.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style TargetType="local:PropertyEditControl">
<Setter Property="Validation.ErrorTemplate" Value="{StaticResource ValidationErrorTemplate}" />
</Style>
<Style x:Key="PropertyNameStyle" TargetType="DockPanel">
<Setter Property="Width" Value="{Binding ControlWidth}" />
<Setter Property="DockPanel.Dock" Value="Left" />
</Style>
...
如果我删除它有效的<Style TargetType="local:PropertyEditControl">
样式!
答案 0 :(得分:0)
事实证明我的原始方法应该有效。之所以没有在用户控件中放错了Style Resource。无论如何,我最初问题的正确答案是:要为多个控件设置一次DependencyProperty值,您必须在容器样式定义中设置它:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type propwin:PropertyEditControl}">
<Setter Property="ControlWidth" Value="180" />
</Style>
</StackPanel.Resources>
<propwin:PropertyEditControl Label="First" />
<propwin:PropertyEditControl Label="Second" />
...
</StackPanel>