繁体   English   中英

PriorityBinding-对Label中的每个绑定使用不同的StringFormat

[英]PriorityBinding - Use different StringFormat for each binding in a Label

在我的WPF项目中,我有一个Label

<Label Grid.Column="1"
       Grid.Row="1">
    <PriorityBinding>
        <Binding Path="Worker.Employer.Name" StringFormat="Employer: {0}" />
        <Binding Source="Unemployed" />
    </PriorityBinding>
</Label>

StringFormat似乎没有执行任何操作。 但是,如果我添加以下内容:

<Label.ContentStringFormat>
    Employer: {0}
</Label.ContentStringFormat>

...格式有效,但是会影响两个绑定。 如何将StringFormat仅应用于顶部绑定?

更新:这么不使用TextBlock而不是Label ,有什么方法可以做到这一点?

StringFormat用于字符串(例如TextBlock.Text),但是label.Content是对象的类型,因此您必须将ContentStringFormat用于Label。

编辑:对您的问题-如果您可以将标签更改为TextBlock,那么您就不再有问题了。 但是,如果您想留下标签,我想您必须使用转换器来应用您的字符串格式。

如前所述,StringFormat仅在目标属性类型为text时有效。

一种解决方案是使用ValueConverter格式化结果,您可以将格式字符串作为ConverterParameter传入。

无法创建附加的字符串类型的DependencyProperty

public static class Helper {
    public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached("Text", typeof(string), typeof(Helper));

   public static string GetText(DependencyObject o) {
     return (string)o.GetValue(TextProperty);
   }

   public static void SetText(DependencyObject o, string value) {
      o.SetValue(TextProperty,value);
   }
}

那你可以做

<Label Grid.Column="1"
       Grid.Row="1" 
       Content="{Binding RelativeSource={RelativeSource Self}, Path=(ui:Helper.Text)}">
    <ui:Helper.Text>
    <PriorityBinding>
        <Binding Path="Worker.Employer.Name" StringFormat="Employer: {0}" />
        <Binding Source="Unemployed" />
    </PriorityBinding>
    </ui:Helper.Text>
</Label>

注释中描述的问题可能与此问题有关 ,因此XAML可能需要看起来像这样。

<Label Grid.Column="1"
       Grid.Row="1" >
       <Binding RelativeSource="{RelativeSource Self}"  Path="(ui:Helper.Text)" />
      <ui:Helper.Text>
      <PriorityBinding>
          <Binding Path="Worker.Employer.Name" StringFormat="Employer: {0}" />
          <Binding Source="Unemployed" />
      </PriorityBinding>
      </ui:Helper.Text>
</Label>

或者从这个MSDN问题中您可以做

<Label Grid.Column="1"
       Grid.Row="1" >
      <ui:Helper.Text>
      <PriorityBinding>
          <Binding Path="Worker.Employer.Name" StringFormat="Employer: {0}" />
          <Binding Source="Unemployed" />
      </PriorityBinding>
      </ui:Helper.Text>
      <Label.Content>
         <Binding RelativeSource="{RelativeSource Self}"  Path="(ui:Helper.Text)" />
      </Label.Content>
    </Label>

确保将ui的xmlns绑定到Helper类的名称空间

您始终可以将“内容”相对源绑定放入一种样式中,以避免对所有标签重复进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM