c# - 当绑定(bind)属性声明为接口(interface)类型与类类型时,WPF 绑定(bind)行为不同?

标签 c# .net wpf data-binding xaml

这始于我认为与我的 ToString() 实现有关的奇怪行为,我问了这个问题:Why won't WPF databindings show text when ToString() has a collaborating object?

事实证明与合作者无关,可重现。

当我将 Label.Content 绑定(bind)到声明为接口(interface)类型的 DataContext 的属性时,将调用 ToString()运行时对象和标签显示结果。

当我将 TextBlock.Text 绑定(bind)到同一属性时,永远不会调用 ToString() 并且不会显示任何内容。 但是,如果我将声明的属性更改为接口(interface)的具体实现,它会按预期工作。

这是设计使然吗?如果是这样,知道为什么吗?

重现:

  • 创建一个新的 WPF 应用程序 (.NET 3.5 SP1)
  • 添加以下类:
public interface IFoo
{
    string foo_part1 { get; set; }
    string foo_part2 { get; set; }
}

public class Foo : IFoo
{
    public string foo_part1 { get; set; }

    public string foo_part2 { get; set; }

    public override string ToString() 
    { 
        return foo_part1 + " - " + foo_part2; 
    }
}
public class Bar
{
    public IFoo foo 
    { 
        get { return new Foo {foo_part1 = "first", foo_part2 = "second"}; } 
    }
}
  • 将 Window1 的 XAML 设置为:

    <Window x:Class="WpfApplication1.Window1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/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 中:

public partial class Window1 : Window  
{  
    public Window1()  
    {  
        InitializeComponent();  
        DataContext = new Bar();  
    }  
}

当您运行此应用程序时,您只会看到一次文本(在顶部的标签中)。如果将 Bar 类的 foo 属性的类型更改为 Foo(而不是 IFoo)并运行应用程序同样,您会在两个控件中看到文本。

最佳答案

我知道这个帖子很旧,但我找到了解决这个问题的方法。在绑定(bind)上使用 StringFormat 属性:

<Window x:Class="WpfApplication1.Window1"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/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>

关于c# - 当绑定(bind)属性声明为接口(interface)类型与类类型时,WPF 绑定(bind)行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2917878/

相关文章:

c# - 使用我无法修改的类的私有(private)构造函数模拟对象

c# - 有没有办法在 Switch 表达式中跳过或继续,或者每个分支都需要返回一些东西?

c# - 如何根据 ID 从员工薪水第二高的员工集合中选择具有 LINQ 的不同员工?

c# - 选项卡更改时刷新/重新加载 MUI WPF 页面

c# - SSMS 中的网格控件

c# - 未在 Windows 服务中获取 OnStart 事件日志条目

c# - 使用JavaScript从Com Visible dll调用.net dll时出错

c# - 如何列出 NuGet v3 API 中的所有本地包

.net - System.Drawing 和垃圾收集

C# 文本框中没有 PasswordChar 字段