当Binding源本身就是数据且不需要Path来指明时,可以设置Path的值为".",或直接省略Path。XAML中这个"."可以省略不写,但在C#代码中是不能省略的。
XAML:
<Window x:Class="没有Path的Binding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" Title="MainWindow" Height="155.129" Width="209.615" Loaded="Window_Loaded"> <Grid> <StackPanel> <StackPanel.Resources> <sys:String x:Key="myString"> 菩提本无树,明镜亦非台。 本来无一物,何来惹尘埃。 </sys:String> </StackPanel.Resources> <TextBlock x:Name="textBlock1" TextWrapping="Wrap" Text="{Binding Path=.,Source={StaticResource ResourceKey=myString}}" FontSize="16" Margin="5" Background="Yellow"></TextBlock> <!--标准的写法是上面那个,下面这两个也是一样的--> <!--<TextBlock x:Name="textBlock1" TextWrapping="Wrap" Text="{Binding .,Source={StaticResource ResourceKey=myString}}" FontSize="16" Margin="5" Background="Yellow"></TextBlock>--> <!--<TextBlock x:Name="textBlock1" TextWrapping="Wrap" Text="{Binding Source={StaticResource ResourceKey=myString}}" FontSize="16" Margin="5" Background="Yellow"></TextBlock>--> <TextBlock x:Name="textBlock2" FontSize="16" Margin="5" TextWrapping="Wrap" Background="Green"></TextBlock> </StackPanel> </Grid> </Window>
C#:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace 没有Path的Binding { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { string str = "菩提本无树,明镜亦非台。本来无一物,何来惹尘埃。"; this.textBlock2.SetBinding(TextBlock.TextProperty, new Binding(".") { Source = str }); } } }
截图: