Skip to main content
 首页 » 编程设计

c#之如何将公共(public)属性绑定(bind)到 WPF TextBox.Text 属性

2024年02月23日16insus

我一直在努力将 TextBox.Text 绑定(bind)到某个对象的公共(public)属性,但不幸的是我还没有做到这一点。

实际的 XAML 看起来像:

<Window  
    <!-- skipped -->  
    xmlns:local="clr-namespace:Dotnet.Samples.Foobar" 
    xmlns:system="clr-namespace:System;assembly=mscorlib"> 
 
    <Window.Resources> 
        <local:Foobar x:Key="foobar" Foo="Lorem" Bar="Ipsum" 
    </Window.Resources> 
    <!-- skipped --> 
 
        <TextBox Text="{Binding Source={StaticResource foobar}, Path=Foo}"> 
        <TextBox Text="{Binding Source={StaticResource foobar}, Path=Bar}"> 
        <!-- skipped --> 
</Window> 

数据提供者对象很简单:

public class Foobar 
{ 
    public string Foo { get; set; } 
    public string Bar { get; set; } 
 
    public Foobar() 
    { 
 
    } 
} 

我想我对 WPF 的各种绑定(bind)选项有点困惑,我可能会把它们混在一起,所以任何建议都将不胜感激。

编辑——所有绑定(bind)工作正常,剩下的挑战是通知从模型到 View 模型的变化(反之亦然)。我已将“损坏的”代码提交给另一个 repo 协议(protocol): http://nanotaboada.svn.beanstalkapp.com/dotnet/trunk/Dotnet.Samples.Rijndael/

请随时结帐,我很乐意听到有关此的任何反馈。提前致谢

请您参考如下方法:

XAML 绑定(bind)引擎找不到合适的构造函数来使用,即使您的构造函数方法参数是可选的。因此,您要么必须传入构造函数的值,要么创建一个将 Foo 的值设置为默认值的无参数构造函数,或者根本不使用 ObjectDataProvider,直接创建您的类型的实例作为资源。

... 
xmlns:system="clr-namespace:System;assembly=mscorlib" 
... 
 
<!-- Either create an instance of your type, and you can initialise the property values, this will require a default parameterless constructor --> 
<abc:Foobar x:Key="foobar2" Foo="Foo" /> 
 
<!-- or pass the optional parameter values into your existing constructor --> 
<ObjectDataProvider x:Key="foobar" ObjectType="{x:Type abc:Foobar}"> 
  <ObjectDataProvider.ConstructorParameters> 
    <system:String>Foo</system:String> 
    <system:String>Bar</system:String> 
  </ObjectDataProvider.ConstructorParameters> 
</ObjectDataProvider> 

请注意,如果您的绑定(bind)将在代码中失效,您只需要实现 INotifyPropertyChanged,并且您需要通知 UI。如果您不喜欢在您的模型类型上实现此接口(interface),那么您可以在您的 View 模型上执行此操作(假设您使用的是 MVVM),但是您需要找到另一种机制来在您的模型时通知您的 View 模型值(value)观改变。