wpf根据数据应用staticresouce

时间:2010-09-24 20:27:33

标签: wpf binding styles

如何根据数据按名称应用静态资源?我知道我可以为样式属性编写数据触发器,但我想根据绑定数据应用整个样式。

例如:
if(condition)CellValuePresenterStyle =“{StaticResource OptionalFieldCellPresenter}” else CellValuePresenterStyle =“{StaticResource RequiredFieldCellPresenter}”

2 个答案:

答案 0 :(得分:2)

您可以编写自定义转换器来处理此问题。 Converter类看起来像这样:

//''' <summary>
//''' Returns a Style  based upon the text that is passed into the Convert
//''' function in the 'value' object.
//''' </summary>
//''' <remarks></remarks>
Public Class NameToStyleConverter
   Implements IValueConverter

   Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
      Dim styleName As String = CStr(value)
      Dim styl As System.Windows.Style

      styl = Application.Current.TryFindResource(styleName)

      Return styl

   End Function

   Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
      Throw New NotImplementedException("This method or operation is not implemented.")
   End Function
End Class

在您的窗口的XAML中,您将拥有以下内容:

<Window.Resources>
    <local:NameToStyleConverter x:Key="NameToStyleConverter"/>
</Window.Resources>

其中'local'是应用程序的已定义命名空间。

实施可能如下所示:

Style="{Binding Path=MyStyleNameText, Converter={StaticResource NameToStyleConverter}"

或者可选地,您始终可以从代码中引用转换器。传入一个字符串,它返回一个样式。

答案 1 :(得分:1)

将样式应用于父控件,看起来您正在使用DataGrid,并使用默认的CellStyleTemplate。

然后在Style.Triggers中添加数据触发器,以便在满足条件时将样式交换为另一种样式