【问题标题】:Dependency Property of Style typeStyle 类型的依赖属性
【发布时间】:2014-04-08 20:13:58
【问题描述】:

我想将 Style 公开为依赖属性。基本上中间有一个矩形指示器,使用控件将公开一个样式依赖属性,用于包含要设置的控件。它将允许那些包含控件的人根据他们自己对项目的了解来提供一种着色样式。

<ItemsControl ItemsSource="{Binding Rows}">
   <ItemsControl.ItemTemplate>
       <DataTemplate>
           <StackPanel Orientation="Horizontal">
               <TextBlock Text="{Binding RowName}"/>
               <ItemsControl ItemsSource="{Binding Statuses}">

                    <Rectangle Style="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Path=RectangleStyle}"/>
               </ItemsControl>
           </StackPanel>
       </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

自定义控件代码隐藏中的依赖属性。

    public Style RectangleStyle
    {
        get { return (Style)GetValue(RectangleStyleProperty); }
        set { SetValue(RectangleStyleProperty, value); }
    }

    public static readonly DependencyProperty RectangleStyleProperty =
        DependencyProperty.Register("RectangleStyle", typeof(Style), typeof(MyControl), new PropertyMetadata(null));

然后会像这样使用:

    <MyControl>
        <MyControl.RectangleStyle>
            <Style TargetType="{x:Type Rectangle}">
                <Setter Property="Fill" Value="Red"/>
            </Style>
        </MyControl.RectangleStyle>
    </MyControl>

这根本不起作用,我不确定我的方法是否正确。

【问题讨论】:

    标签: wpf wpf-controls dependency-properties


    【解决方案1】:

    愚蠢的语法错误。我需要为内部 ItemsControl 设置 ItemsTemplate。我将 ItemsControl 的内容设置为 Rectangle。

    <ItemsControl ItemsSource="{Binding Rows}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding RowName}"/>
                    <ItemsControl ItemsSource="{Binding Statuses}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal"/>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <Rectangle Style="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Path=RectangleStyle}"/>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 2021-04-02
      • 2016-11-29
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      相关资源
      最近更新 更多