1.先在Converter命名空間當中,定義轉換功能類:app
public sealed class BoolToValueConverter : System.Windows.Data.IValueConverterspa
{
public object TrueValue
{
get { return trueValue; }
set { trueValue = value; }
}
object trueValue;
public object FalseValue
{
get { return falseValue; }
set { falseValue = value; }
}
object falseValue;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DependencyProperty.UnsetValue;
var data = value.GetType().Name;
if (value.GetType().Name.ToLower().Contains("int")|| value.GetType().Name == "Decimal")
{
if (int.Parse(value.ToString()) !=0)
{
return TrueValue;
}
else
{
return FalseValue;
}
}
if (bool.TryParse(value.ToString(), out bool
result))
{
if (result)
return TrueValue;
else
return FalseValue;
}
else if (Enum.TryParse(value.ToString(), out Visibility
Enumresult))
{
if (Enumresult == Visibility.Visible)
return TrueValue;
else
return FalseValue;
}
else
{
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
2.引用命名空間
xmlns:converter="clr-namespace:Converter"
3.使用方法:
在ResourceDictionary當中調用:
<converter:BoolToValueConverter x:Key="BoolToColorConverter" TrueValue="#3F48CC" FalseValue="#ED1C24"/>
<TextBlock TextWrapping="Wrap" Grid.Column="1" Text="{Binding IsSensitiveArea,Converter={StaticResource BoolToColorConverter}}"/>
在window當中定義和調用:
<window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Infrastructure;component\Style\Themes\Style.xaml" />
</ResourceDictionary.MergedDictionaries>
<converter:BoolToValueConverter x:Key="BoolToValueConverterOnWord" TrueValue="是" FalseValue="否"/>
</ResourceDictionary>
</window.Resources>
<TextBlock TextWrapping="Wrap" Grid.Column="1" Text="{Binding IsSensitiveArea,Converter={StaticResource BoolToValueConverterOnWord}}"/>