Binding对象的属性
Property | Description |
| 转换器 |
| 绑定的源对象 |
| 绑定无法返回有效值时的默认显示。 |
| 绑定方式 |
| 属性 |
| 常用于自身绑定或者数据模板中来指定绑定的源对象。 |
| 源对象 |
| 格式化表达式 |
| Sets the events on which binding will occur. |
| 验证规则 |
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="UntitledProject2.Window1"
x:Name="Window"
Title="Window1"
Width="640" Height="480">
<Grid x:Name="LayoutRoot">
<Label HorizontalAlignment="Left" Margin="36,34,0,0" VerticalAlignment="Top" Width="106" Height="33" Content="Color"/>
<ListBox HorizontalAlignment="Left" Margin="85,67,0,0" VerticalAlignment="Top" Width="151" Height="90" IsSynchronizedWithCurrentItem="True" x:Name="lbColor">
<ListBoxItem x:Name="red" Content="Red"/>
<ListBoxItem x:Name="green" Content="Green"/>
<ListBoxItem x:Name="blue" Content="Blue"/>
</ListBox>
<Label HorizontalAlignment="Left" Margin="36,183,0,221" Width="156" Content="You select color:"/>
<TextBlock Margin="85,0,292,145" VerticalAlignment="Bottom" Height="62" Text = "{Binding ElementName = lbColor,Path=SelectedItem.Content,Mode=OneWay}" TextWrapping="Wrap"/>
</Grid>
</Window>
运行效果
加上一句话,改变TextBlock的背景颜色
Background="{Binding ElementName=lbColor,Path=SelectedItem.Content,Mode=OneWay}"
运行效果:
xml文件绑定:
首先编写一个xml文件eg.xml
<?xml version="1.0" ?>
<!-- File Name: eg.xml -->
<colors xmlns="">
<color name = "pink" ID ="1" />
<color name = "white" ID ="2" />
<color name = "black" ID ="3" />
<color name = "yellow" ID ="4"/>
<color name = "blue" ID ="5"/>
<color name = "red" ID ="6"/>
<color name = "brown" ID ="7"/>
<color name = "purple" ID ="8"/>
<color name = "green" ID ="9"/>
</colors>
xaml代入如下:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="UntitledProject4.Window1"
x:Name="Window"
Title="Window1"
Width="640" Height="480">
<Window.Resources>
<XmlDataProvider x:Key="colorbox" Source="eg.xml" XPath="colors" />
</Window.Resources>
<Grid x:Name="LayoutRoot">
<ListBox Margin="81,78,274,173" ItemsSource="{Binding Source={StaticResource colorbox},XPath=color/@name}" IsSynchronizedWithCurrentItem="True" x:Name="cb" SelectionChanged="cb_SelectionChanged"/>
<TextBox Margin="81,0,274,84" VerticalAlignment="Bottom" Height="40" Text="{Binding ElementName=cb,Path=SelectedItem.Content,Mode=OneWay}" TextWrapping="Wrap" x:Name="result"/>
</Grid>
</Window>
这里只是把xml文件里的colors/color/name绑定到listbox里,要想在textblock里显示颜色,那么需要添加一个listbox的触发事件selectionchanged,代码如下:
private void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string s1 = cb.SelectedValue.ToString();
result.Text = s1;
Color c1 = (Color)ColorConverter.ConvertFromString(s1); //string to color
Brush b1 = new SolidColorBrush(c1); //color to brush
result.Background = b1;
}
然后运行结果如下: