天天看點

WPF XAML之bing使用StringFormat

釋義

BindingBase.StringFormat 屬性

擷取或設定一個字元串,該字元串指定如果綁定值顯示為字元串,應如何設定該綁定的格式。
           

命名空間: System.Windows.Data

程式集: PresentationFramework(在 PresentationFramework.dll 中)

用于 XAML 的 XMLNS:http://schemas.microsoft.com/winfx/2006/xaml/presentation, http://schemas.microsoft.com/netfx/2007/xaml/presentation

StringFormat和Converter

如果設定 Converter 和 StringFormat 屬性,則會先對資料值應用轉換器,然後應用 StringFormat。

使用

1:Binding中使用StringFormat, StringFormat 設定為撰寫字元串格式時,隻能指定一個參數。如綁定Name:

<ListView ItemsSource="{StaticResource MyData}">
  <ListView.View>
    <GridView>
      <GridViewColumn DisplayMemberBinding="{Binding Path=Description}"/>
      <GridViewColumn DisplayMemberBinding="{Binding Path=Price, StringFormat=Now {0:c}!}"/>
      <GridViewColumn DisplayMemberBinding="{Binding Path=Price, StringFormat={}{0:c}!}"/>
    </GridView>
  </ListView.View>
</ListView>
           
注意:
    如果StringFormat中沒有字元,“StringFormat=”後面需要先加入“{}”。
    如果StringFormat中有字元,則不需要加入“{}”
           

2:綁定格式化時間

或者

3:多重綁定

<ListBox ItemsSource="{StaticResource MyData}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock>
        <TextBlock.Text>
          <MultiBinding  StringFormat="{}{0} -- Now only {1:C}!">
            <Binding Path="Description"/>
            <Binding Path="Price"/>
          </MultiBinding>
        </TextBlock.Text>
      </TextBlock>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
           

4:多重綁定中的特殊字元, 如 \t

<TextBlock.Text>
    <MultiBinding StringFormat="Delete {0}&#x09;{1}">
        <Binding Path="FirstName" />
        <Binding Path="LastName" />
    </MultiBinding>
 </TextBlock.Text>
           

特殊字元如下:

WPF XAML之bing使用StringFormat

5,在使用 PriorityBinding 時,可以在 PriorityBinding 和/或子綁定對象上設定 StringFormat。

<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"
  DataContext="{Binding Source={StaticResource AsyncDS}}">
        <Te
        xtBlock FontSize="18" FontWeight="Bold" Margin="10"  HorizontalAlignment="Center">Priority Binding</TextBlock>
        <TextBlock Background="Honeydew" Width="100" HorizontalAlignment="Center">
            <TextBlock.Text>
                <PriorityBinding FallbackValue="defaultvalue">
                    <Binding Path="SlowestDP" IsAsync="True"/>
                    <Binding Path="SlowerDP" IsAsync="True"/>
                    <Binding Path="FastDP" />
                </PriorityBinding>
            </TextBlock.Text>
        </TextBlock>
    </StackPanel>
           
上一篇: 倒序排列