这是以我以为与 ToString()的实现有关的奇怪行为开始的,我问了这个问题:
This started with weird behaviour that I thought was tied to my implementation of ToString(), and I asked this question: Why won't WPF databindings show text when ToString() has a collaborating object?
事实证明与协作者无关,可重复。
It turns out to have nothing to do with collaborators and is reproducible.
当我绑定 Label.Content 被声明为接口类型的 DataContext 的属性, ToString ()在运行时对象上被调用,标签显示结果。
When I bind Label.Content to a property of the DataContext that is declared as an interface type, ToString() is called on the runtime object and the label displays the result.
当我绑定 TextBlock.Text 到同一个属性, ToString()永远不会被调用,没有显示任何内容。 但是,如果我将声明的属性更改为接口的具体实现,它的工作原理如下。
When I bind TextBlock.Text to the same property, ToString() is never called and nothing is displayed. But, if I change the declared property to a concrete implementation of the interface, it works as expected.
这是不是设计?如果是这样,任何想法为什么?
Is this somehow by design? If so, any idea why?
要复制:
- 创建一个新的WPF应用程序(.NET 3.5 SP1)
- 添加以下类:
public class Bar { public IFoo foo { get { return new Foo {foo_part1 = "first", foo_part2 = "second"}; } } }
-
将Window1的XAML设置为:
Set the XAML of Window1 to:
<Window x:Class="WpfApplication1.Window1" xmlns="schemas.microsoft/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <StackPanel> <Label Content="{Binding foo, Mode=Default}"/> <TextBlock Text="{Binding foo, Mode=Default}"/> </StackPanel> </Window>-
在Window1.xaml.cs中:
in Window1.xaml.cs:
public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = new Bar(); } }当你运行这个应用程序,你会看到文本只有一次(在顶部的标签中)。如果您将 Bar 类中的 foo 属性的类型更改为 Foo (而不是 IFoo )并再次运行应用程序,您将看到两个控件中的文本。
When you run this application, you'll see the text only once (at the top, in the label). If you change the type of foo property on Bar class to Foo (instead of IFoo) and run the application again, you'll see the text in both controls.
推荐答案我知道这个线程很旧,但是我发现这个问题的解决方法。使用绑定上的StringFormat属性:
I know this thread is old but I found a workaround for this problem. Use the StringFormat property on the binding:
<Window x:Class="WpfApplication1.Window1" xmlns="schemas.microsoft/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <StackPanel> <Label Content="{Binding foo, Mode=Default}"/> <TextBlock Text="{Binding foo, Mode=Default, StringFormat={}{0}}"/> </StackPanel> </Window>
更多推荐
当绑定属性被声明为接口vs类类型时,WPF绑定行为不同?
发布评论