代码改变世界

初次使用wpf 转换器

2017-11-14 22:52  蛋蛋01  阅读(192)  评论(0)    收藏  举报

一,转换器定义

 

 

单值转换器定义

 

public partial class RedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
InOutFlag inOutFlag = (InOutFlag)value;
return inOutFlag == InOutFlag.出账 ? Brushes.Red : Brushes.Black;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
}

 

 

多只转换器定义

 

 

public partial class TeachingModeStringFormatConverter : IMultiValueConverter
{
public object Convert(object[] value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
TeachingMode teachingMode = (TeachingMode)value[0];
string otherStr = "报名";
switch (teachingMode)
{
case TeachingMode.全日制住宿:
return TeachingMode.全日制住宿.ToStringOrEmpty() + otherStr;
case TeachingMode.全日制走读:
return TeachingMode.全日制走读.ToStringOrEmpty() + otherStr;
case TeachingMode.兴趣班:
return TeachingMode.兴趣班.ToStringOrEmpty() + otherStr;
case TeachingMode.开放课:
return TeachingMode.开放课.ToStringOrEmpty() + otherStr;
default:
return "";
}
}

public object[] ConvertBack(object value, Type[] targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}

 

单值和多值的区别只是在于 传参数的不同。单值定义的参数是object value  多值定义的是 object[] value

 

 

二,页面使用  

资源引进

<Window x:Class="AM.Moduals.ElderlyAccountCostInfo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:common="clr-namespace:AM.Common;assembly=AMCommon"
xmlns:local="clr-namespace:AM.Control"
Style="{DynamicResource CustomPopupWindowStyle}" WindowStartupLocation="CenterScreen" Width="900" Height="700">
<Window.Resources>
<common:RedConverter x:Key="RedConverter" />
</Window.Resources>

</Window>

 

页面使用单值

 

<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" TextWrapping="Wrap"
Text="{Binding Path=Amount}" Foreground="{Binding InOutFlag,Converter={StaticResource RedConverter}}"/>

InOutFlag 就是定义的  object value 

 

页面是有多值

 

<MenuItem Header="编辑" Style="{DynamicResource MenuItemBaseStyle}" Width="110" Name="btnEdit" Tag="{Binding ReservationID}" Click="btnEdit_Click">
<MenuItem.Visibility>
<MultiBinding Converter="{StaticResource CloseFlagAndFunctionFlagToVisibilityConverter}">
<Binding Path="CloseFlag"/>
<Binding Path="UniversityReservationEdit" RelativeSource="{RelativeSource AncestorType=UserControl}"></Binding>
</MultiBinding>
</MenuItem.Visibility>
</MenuItem>