WPF多值绑定及多值转换(MultiBinding和IMultiValueConverter)

WPF可以使用MultiBinding进行多值绑定,使用IMultiValueConverter进行多值转换

例:

(1)转换器

    public class ContentConverter : IMultiValueConverter
    {
        //源属性传给目标属性时,调用此方法ConvertBack
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values == null || values.Length == 0)
                throw new ArgumentNullException("values can not be null");

            string s = "";
            foreach (var item in values)
            {
                s += System.Convert.ToString(item);
            }

            return s;
        }

        //目标属性传给源属性时,调用此方法ConvertBack
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

(2)绑定

    <Window.Resources>
        <local:ContentConverter x:Key="content"></local:ContentConverter>
    </Window.Resources>
    <Grid>
        <Label HorizontalAlignment="Left" Height="23" Margin="243,208,0,0" Foreground="{Binding Status,Converter={StaticResource foreColor},Mode=OneWay}" VerticalAlignment="Top" Width="120">
            <Label.Content>
                <MultiBinding Converter="{StaticResource content}">
                    <Binding Path="Str1"/>
                    <Binding Path="Str2"/>
                    <Binding Path="Str3"/>
                </MultiBinding>
            </Label.Content>
        </Label>
        <Button Content="Button" HorizontalAlignment="Left" Margin="35,44,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>

(3)button click事件

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            window2ViewModel.Str1 = "1";
            window2ViewModel.Str2 = "2";
            window2ViewModel.Str3 = "3";
        }

(4)效果  lable显示 str1,str2和str3相加后的字符串

 

 

  

 

转载于:https://www.cnblogs.com/yaosj/p/11240275.html

已标记关键词 清除标记
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页