WPF 变量转换的实现

   有时候,我们传入的是一个值,但是真正显示的需要是另一个值,这时候就需要转换。比如我们传入一个枚举值,而不同的枚举值对于的图片是不一样的。

   这时候就需要一个转换规则。WPF里面给我们提供了一个接口IValueConverter。我们可以自己新建一个类继承该接口,然后写自己的转换规则。

   我们新建一个类:

  

 class ChangeValueToResult : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string strValue = (string)value;

            if (strValue.Equals("1"))
            {
                strValue = "images/1.png";
            }
            else if (strValue.Equals("2"))
            {
                strValue = "images/2.png";
            }
            
            return strValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

  MainWindow.xaml

   这里先引入该转换类:

<Window.Resources>
        <ResourceDictionary>
            <local:ChangeValueToResult x:Key="changeValueToResult"></local:ChangeValueToResult>
        </ResourceDictionary>
    </Window.Resources>

使用的地方:

 <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="40" Margin="28,42,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="176"/>
 <TextBox x:Name="textBox2" HorizontalAlignment="Left" Height="51" Margin="28,118,0,0" TextWrapping="Wrap" 
Text="{Binding ElementName=textBox1, Path=Text ,Converter={StaticResource changeValueToResult}}"
VerticalAlignment="Top" Width="176"/>

上面的代码意思是:

textBox2的值是根据textBox1的值来进行变化的。而变化规则是根据changeValueToResult来定的。

效果如下:


posted @ 2016-12-24 15:53  高山百川  阅读(556)  评论(0编辑  收藏  举报