wpf apply staticresouce based upon data
How can I apply a static resource by name based upon data? I know that I can write a data trigger for styling properties, but I want to apply an e开发者_JS百科ntire style based upon bound data.
Ex:
if (condition) CellValuePresenterStyle="{StaticResource OptionalFieldCellPresenter}" else CellValuePresenterStyle="{StaticResource RequiredFieldCellPresenter}"You can write a custom converter to take care of this. The Converter class would look like this:
//''' <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
In the XAML for your window, you would have the following:
<Window.Resources>
<local:NameToStyleConverter x:Key="NameToStyleConverter"/>
</Window.Resources>
where 'local' is the defined namespace for your application.
Implementation might look like this:
Style="{Binding Path=MyStyleNameText, Converter={StaticResource NameToStyleConverter}"
Or optionally, you can always refer to the Converter from code. You pass in a string and it returns a style.
Apply a style to the parent control, it looks like you are using a DataGrid, with a default CellStyleTemplate.
Then in Style.Triggers add a data trigger to swap the style to another style when a condition is met
精彩评论