WPF使用转换器(Converter)

1.作用:可以将源数据和目标数据之间进行特定的转化,

2.定义转换器,需要继承接口IValueConverter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[ValueConversion(typeof(int), typeof(string))]
public class ForeColorConverter : IValueConverter
{
    //源属性传给目标属性时,调用此方法ConvertBack
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int c = System.Convert.ToInt32(parameter);
 
        if (value == null)
            throw new ArgumentNullException("value can not be null");
 
        int index = System.Convert.ToInt32(value);
        if (index == 0)
            return "Blue";
        else if (index == 1)
            return "Red";
        else
            return "Green";
    }
 
    //目标属性传给源属性时,调用此方法ConvertBack
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
} 


public ValueConversionAttribute(Type sourceType, Type targetType):指定源属性类型和目标属性类型

Convert:会进行源属性传给目标属性的特定转化

ConvertBack:会进行目标属性传给源属性的特定转化

参数parameter:对应Binding的ConverterParameter属性

3.使用转换器

(1)引用转换器所在的命名空间

1
xmlns:local1="clr-namespace:WpfTest.View"

(2)定义资源

1
2
3
<Window.Resources>
    <local1:ForeColorConverter x:Key="foreColor"></local1:ForeColorConverter>
</Window.Resources>

(3)定义属性

1
2
3
4
5
6
private int status = 0;
public int Status
{
    get => status; set { status = value; RaisePropertyChanged("Status"); }
 
}

(4)绑定属性,添加转换器

1
2
3
4
5
<Grid>
    <Label HorizontalAlignment="Left" Height="23" Margin="243,208,0,0" Content="这里哦" Foreground="{Binding Status,Converter={StaticResource foreColor},Mode=OneWay}" VerticalAlignment="Top" Width="120"/>
    <TextBox x:Name="tbName" HorizontalAlignment="Left" Height="23" Margin="243,160,0,0" TextWrapping="Wrap" Text="{Binding Status,UpdateSourceTrigger=LostFocus,Mode=OneWayToSource}" VerticalAlignment="Top" Width="120"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="389,160,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>

4.效果

 

 

 

 

 

posted @   翻白眼的哈士奇  阅读(21336)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示