【问题标题】:wpf apply staticresouce based upon datawpf 根据数据应用静态资源
【发布时间】:2010-09-24 20:27:32
【问题描述】:

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

例如:
if (条件) CellValuePresenterStyle="{StaticResource OptionalFieldCellPresenter}" 否则 CellValuePresenterStyle="{StaticResource RequiredFieldCellPresenter}"

【问题讨论】:

    标签: wpf binding styles


    【解决方案1】:

    您可以编写一个自定义转换器来处理这个问题。 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>
    

    其中“本地”是为您的应用程序定义的命名空间。

    实现可能如下所示:

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

    或者,您可以随时从代码中引用转换器。你传入一个字符串,它会返回一个样式。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我喜欢这个想法,但我认为我的示例可能具有误导性。如果我在样式中编写数据触发器,那么替换样式将删除数据触发器 - 对吗?
      • 如果您给样式一个键并在新样式中使用 BasedOn 属性,则不会
      猜你喜欢
      • 2022-12-04
      • 1970-01-01
      • 2010-10-25
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      相关资源
      最近更新 更多