ItemTemplate中的WPF ItemsControl访问控制

时间:2017-05-05 15:24:09

标签: wpf itemscontrol

我有一个带有简单项目模板的ItemsControl,如下所示:

<ItemsControl x:Uid="itemsControlMarketingText" x:Name="itemsControlMarketingText">
    <ItemsControl.ItemTemplate>
        <DataTemplate x:Name="dataTemplateMarketingText">
            <BulletDecorator x:Uid="bdMarketingTextBullet" x:Name="bdMarketingTextBullet" Width="Auto" >
                <BulletDecorator.Bullet>
                    <Ellipse Width="5" Height="5" Fill="Black" Margin="8,0,0,0"></Ellipse>
                </BulletDecorator.Bullet>
                <TextBlock x:Uid="tbMarketingTextItem" x:Name="tbMarketingTextItem" Text="{Binding}" ></TextBlock>
            </BulletDecorator>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我想在后面的代码中设置tbMarketingTextItem的样式,因此它适用于填充列表时创建的所有文本块。所以基本上就像我在文本块上有一个Style属性一样,如

<Style="{DynamicResource BaseTextBlockMarketingText}"

问题在于这个特定的应用程序,它正在做一些事情来合并不同的样式表并在代码隐藏中应用样式。有没有办法从数据模板中获取控件以应用样式?我怀疑我必须以某种方式使用“FindName”方法,但我无法弄清楚如何。

1 个答案:

答案 0 :(得分:0)

只需使用FindResource()将Style定义为资源,然后将setter等合并到其中,无论您从何处获取它们。

如果您需要在首次使用样式后执行此操作,则无效。以下替代方法适用于该情况。

var btnStyle = FindResource("BaseTextBlockMarketingText") as Style;

//  Contrived example
btnStyle.Setters.Add(new Setter(Button.BackgroundProperty, Brushes.YellowGreen));

或者替换它。即使已经使用了样式,这也会起作用,因为您没有改变使用的Style对象。

var btnStyle = new Style();

//  Contrived example
btnStyle.Setters.Add(new Setter(Button.BackgroundProperty, Brushes.YellowGreen));

this.Resources["BaseTextBlockMarketingText"] = btnStyle;

XAML

<Style 
    x:Key="BaseTextBlockMarketingText" 
    TargetType="Button" 
    BasedOn="{StaticResource {x:Type Button}}"
    />

...

<Button
    Style="{DynamicResource BaseTextBlockMarketingText}"
    />

替代解决方案

使按钮样式成为视图的属性。 Window,UserControl,没关系。下面我的XAML将假设它是一个窗口,但它确实无关紧要。

这使我们可以替换样式而不是更改现有样式实例。

#region ButtonStyle Property
public Style ButtonStyle
{
    get { return (Style)GetValue(ButtonStyleProperty); }
    set { SetValue(ButtonStyleProperty, value); }
}

public static readonly DependencyProperty ButtonStyleProperty =
    DependencyProperty.Register(nameof(ButtonStyle), typeof(Style), typeof(MainWindow),
        new PropertyMetadata(null));
#endregion ButtonStyle Property

按照您喜欢的方式初始化它。出于测试目的,我刚刚在视图构造函数中创建了一个快速:

public MainWindow()
{
    InitializeComponent();

    var style = new Style(typeof(Button), FindResource(typeof(Button)) as Style);

    style.Setters.Add(new Setter(Button.BackgroundProperty, Brushes.LightSkyBlue));

    ButtonStyle = style;
}

并像这样使用它。这里的AncestorType参数是唯一重要的地方ButtonStyle特别是Window的属性:

<Button
    Style="{Binding ButtonStyle, RelativeSource={RelativeSource AncestorType=Window}}"
    />

可能是一个viewmodel属性,但Style确实应该是视图的一部分。

相关问题