IValueConvert的例子

在MVVM中经常遇到控制界面显示的问题

下面来一段代码用true和false来控制界面的显示

先写一个类实现接口IValueConvert

 1  public class BoolToVisibilityConvert:IValueConverter
 2     {
 3         public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 4         {
 5             bool trueOrFalse = (bool)value;
 6             string str = trueOrFalse ? "Visible" : "Collapsed";
 7             return str;
 8         }
 9 
10         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
11         {
12             string visibility = (string)value;
13             switch (visibility)
14             {
15                 case "Visible":
16                     return true;
17                 case "Hidden":
18                     return false;
19                 case "Collapsed":
20                     return false;
21                 default:
22                     return false;
23             }
24         }
25     }
BoolToVisibilityConvert

然后再xaml界面定义一下

 1 <Window x:Class="Test1BoolenToVisiableConvert.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:Converter="clr-namespace:Test1BoolenToVisiableConvert"
 5         Title="MainWindow" Height="350" Width="525">
 6     <Window.Resources>
 7         <Converter:BoolToVisibilityConvert x:Key="booltovisibleConvert"/>
 8     </Window.Resources>
 9     <Grid>
10         <TextBlock Text="BoolToVisibleConvert" 
11                    HorizontalAlignment="Center" VerticalAlignment="Center"
12                    Visibility="{Binding ShowText,Converter={StaticResource booltovisibleConvert}}"/>
13     </Grid>
14 </Window>
xaml

那么在对应的ViewModel中就可以用了

1 public class MainWindowViewModel 
2     {
3         public MainWindowViewModel()
4         { ShowText = true; }
5 
6         public bool ShowText { get; set; }
7     }
View Code

简单的一个demo写完了

 

posted @ 2014-01-06 00:16  冰雪乾坤  阅读(361)  评论(0编辑  收藏  举报