如何使用数据绑定更改XAML文件的样式? [英] How can I change styles of XAML file using Data Binding?

查看:92
本文介绍了如何使用数据绑定更改XAML文件的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一组对象绑定到WPF中的一个列表框中,为简单起见,我们将说我绑定的对象有3个属性:Name,URL,IsBold。如果IsBold设置为true,我想要做的是将它显示为不同,再次作为示例,我想设置名称出现的TextBlock为粗体。这样的事情甚至可能吗?如果我的某个属性是某个值,我可以使用不同的样式吗? (我可以像XAML中的if / else这样做)吗?我真的不知道从哪里开始。

I'm binding a collection of objects to a listbox in WPF, for simplicity we'll say the object i'm binding has 3 propertys: Name, URL, IsBold. What I want to do, is have it displayed different if the IsBold is set to true, again as an example I want to set the TextBlock that Name appears in, to be bold. Is something like this even possible? Can I use a different style or something if one of my properties is a certain value? (can I do anything like an if/else in XAML)? I really have no idea where to start with this.

说我在我的DataTemplate中有这个

Say I have this in my DataTemplate

<TextBlock Style="{StaticResource notBold}" Text="{Binding Path=Name}"></TextBlock>

如果IsBold设置为该项目的真实,我希望它(注意样式从'notBold'更改为'isBold')

And if the IsBold is set to true for that particular Item I would like it to be (notice the style changes from 'notBold' to 'isBold')

<TextBlock Style="{StaticResource isBold}" Text="{Binding Path=Name}"></TextBlock>

或类似的东西。我猜这个比较普遍的问题。是否可以根据数据绑定的项目改变某些东西的外观?如果不可能,怎么会这样做?通过代码隐藏?

Or something similar. I guess the more general question. Is it possible to change the apperance of something based on an item that's databound? And if it's not possible, how would something like this be done? Thru the code-behind somehow?

谢谢

推荐答案

'通常做的是为列表中的对象写一个DataTemplate,然后DataTrigger根据IsBold属性设置TextBlock / TextBox的Fontweight。

What you'd normally do is write a DataTemplate for the objects in the list and then have a DataTrigger set the Fontweight of the TextBlock/TextBox based on the IsBold Property.

<DataTemplate DataType="DataItem">
    <TextBlock x:Name="tb" Text="{Binding Name}"/>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding IsBold}" Value="true">
            <Setter TargetName="tb" Property="FontWeight" Value="Bold" />
        </DataTrigger>
        <DataTrigger Binding="{Binding IsBold}" Value="false">
            <Setter TargetName="tb" Property="FontWeight" Value="Normal" />
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

然后,您可以将DataItem的列表设置为ComboBox的ItemsSource属性(通过数据绑定或直接在codebehind myComboBox.ItemsSource = myDataItems )。其余的是由WPF完成的。

You'd then set a list of DataItems to the ItemsSource property of your ComboBox (either by Databinding or directly in the codebehind myComboBox.ItemsSource=myDataItems). The rest is done by WPF for you.

这篇关于如何使用数据绑定更改XAML文件的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆