wpf 使用 MultiBinding 的字符串格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8377471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:12:06  来源:igfitidea点击:

String format using MultiBinding?

wpfxamlmultibindingstring-formatting

提问by Lucifer

I'm trying to display a string in XAML using Label control. Following is my XAML code :

我正在尝试使用 Label 控件在 XAML 中显示字符串。以下是我的 XAML 代码:

<Label Height="28" HorizontalAlignment="Left" Margin="233,68,0,0" Name="label13" VerticalAlignment="Top">
    <Label.Content>
        <MultiBinding StringFormat="{}{0} x {1}">
              <Binding Path="Width" />
              <Binding Path="Height" />
        </MultiBinding>
    </Label.Content>

Width and Height are two properties of my class Movie. I want the label to display : "Width x Height" ex. 800 x 640 However the label control remains empty. Any help is appreciated. I WANT TO DO THIS WITHOUT USING A CONVERTER.

宽度和高度是我的类电影的两个属性。我希望标签显示:“宽 x 高”例如。800 x 640 但是标签控件仍然是空的。任何帮助表示赞赏。我想在不使用转换器的情况下做到这一点。



I have modified my xaml by using a TextBlock instead of Label. But still it wont populate display the output.

我使用 TextBlock 而不是 Label 修改了我的 xaml。但它仍然不会填充显示输出。

<TextBlock Height="28" HorizontalAlignment="Left" Margin="233,68,0,0" Name="label13" VerticalAlignment="Top">
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0} x {1}">
                        <Binding Path="Width" />
                        <Binding Path="Height" />
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>

回答by punker76

you are trying to bind a string to an object. But StringFormat requires its target to be a string type.

您正在尝试将字符串绑定到对象。但 StringFormat 要求其目标是字符串类型。

try putting a TextBlock in your label content and bind your data to it

尝试在您的标签内容中放置一个 TextBlock 并将您的数据绑定到它

<StackPanel>
  <Slider x:Name="sl1" Minimum="10" Maximum="100"/>
  <Slider x:Name="sl2" Minimum="10" Maximum="100"/>
  <Label x:Name="label13" Background="Yellow" Foreground="Black">
    <Label.Content>
        <TextBlock>
          <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} x {1} Test">
              <Binding ElementName="sl1" Path="Value" />
              <Binding ElementName="sl2" Path="Value" />
            </MultiBinding>
          </TextBlock.Text>
        </TextBlock>
    </Label.Content>
  </Label>
</StackPanel>

EDITyour class Movie must implement the INotificationPropertyChanged interface and your two properties must raise the property changed event with their proprty names!

编辑您的类 Movie 必须实现 INotificationPropertyChanged 接口,并且您的两个属性必须使用它们的属性名称引发属性更改事件!

hope this helps

希望这可以帮助