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相加后的字符串

 

 

  

 

posted @ 2019-07-24 19:18  翻白眼的哈士奇  阅读(7575)  评论(0编辑  收藏  举报