Wpf 如何将DependencyProperty值应用于子用户控件?

Wpf 如何将DependencyProperty值应用于子用户控件?,wpf,user-controls,Wpf,User Controls,我在StackPanel中有多个相同自定义用户控件的实例。每个实例都需要相同的DependencyProperty“ControlWidth”。与使用相同属性设置每个用户控件不同,我只想在父StackPanel中设置它一次 <StackPanel> <propwin:PropertyEditControl Label="First" ControlWidth="180" /> <propwin:PropertyEditControl Lab

我在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>

...

...

如果我删除
样式,它会工作

事实证明,我最初的方法应该是有效的。之所以没有,是因为用户控件中的样式资源放错了位置。无论如何,对我的初始问题的正确答案是:要只为多个控件设置一次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>

...

样式中
属性是设置依赖项属性的类型,这是主要条件之一,在您的情况下应该有效。使用
ControlWidth
属性显示
UserControl
的完整代码。这不适用于非样式属性,我猜这意味着什么。。dp将适用于所有样式。@Sankarann这是询问是否正确理解此原则的另一种方式,这很好。。现在可以用了吗?还有其他问题吗?
如果我删除样式,它就可以工作了-这是因为这样的构造应该在
UserControl
之外使用。例如,在
App.xaml
文件中。