WEB开发网
开发学院WEB开发ASP.NET WPF学习笔记10. Binding (3) 阅读

WPF学习笔记10. Binding (3)

 2010-10-11 16:29:53 来源:本站整理   
核心提示:Convert() 有个有趣的的返回结果 "Binding.DoNothing",它的意思是 "暂时取消该绑定",WPF学习笔记10. Binding (3)(4),publicobjectConvert(objectvalue,TypetargetType,objectpara

Convert() 有个有趣的的返回结果 "Binding.DoNothing",它的意思是 "暂时取消该绑定"。

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
  //return value.ToString() == "Male" ? "男" : "女";
  return Binding.DoNothing;
}

注意,DoNothing 和 null 并不是一回事,null 是个有效返回值。

接下来,我们试着将 Sex 转换成 Brush 类型,以便显示不同的颜色。

Window1.xaml.cs

public class SexToBrushConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    return value.ToString() == "Male" ? Brushes.Blue : Brushes.Red;
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

Window1.xaml

<Window x:Class="Learn.WPF.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:my="clr-namespace:Learn.WPF"
  Title="Window1" Height="276" Width="360" WindowStartupLocation="CenterScreen">
  <Window.Resources>
    <my:PersonalList x:Key="personals" >
      <my:Personal Name="Tom" Age="10" Sex="Male" />
      <my:Personal Name="Mary" Age="15" Sex="Female" />
      <my:Personal Name="Jack" Age="12" Sex="Male" />
    </my:PersonalList>
    <my:SexToBrushConverter x:Key="sexToBrushConverter" />
    <DataTemplate DataType="{x:Type my:Personal}">
      <Border x:Name="border1" 
          BorderBrush="{Binding Path=Sex, Converter={StaticResource sexToBrushConverter}}" 
          BorderThickness="1" Padding="5" Margin="5">
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="{Binding Path=Name}" />
          <TextBlock>,</TextBlock>
          <TextBlock Text="{Binding Path=Age}" />
          <TextBlock>,</TextBlock>
          <TextBlock Text="{Binding Path=Sex}" />
        </StackPanel>
      </Border>
    </DataTemplate>
  </Window.Resources>
  <Grid>
    <StackPanel DataContext="{StaticResource personals}">
      <ListBox x:Name="listbox1" ItemsSource="{Binding}">
      </ListBox>
    </StackPanel>
  </Grid>
</Window>

上一页  1 2 3 4 5  下一页

Tags:WPF 学习 笔记

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接