【问题标题】:Binding to property that a class绑定到类的属性
【发布时间】:2013-05-01 15:43:41
【问题描述】:

如何在没有Converter 的情况下使用绑定,如下面的注释代码?

public partial class MainWindow : Window
{
    public MainWindow()
    {ABC = new ABCClass();      
    InitializeComponent();
        //Binding binding = new Binding();
        //binding.Source = this;
        //binding.Path = new PropertyPath("ABC");
        //binding.Mode = BindingMode.OneWay;
        //txtKey.SetBinding(TextBox.TextProperty, binding);
    Binding binding = new Binding();
    binding.Source = this;
    binding.Path = new PropertyPath("ABC");
    binding.Mode = BindingMode.OneWay;
    binding.Converter = new ABCTypeConverter();
    txtKey.SetBinding(TextBox.TextProperty, binding);
}

班级和Converter

public ABCClass ABC { get; set; }
}


public class ABCClass
{
    public int A = 1;
    public int B = 2;
    public int C = 3;

    public override string ToString()
    {
        return (A + B + C).ToString();
    }
}

Converter 代码已被删除,因为站点编辑器不允许“大部分代码”。此代码不需要“模式详细信息”。

【问题讨论】:

    标签: wpf binding properties converter


    【解决方案1】:

    WPF 不支持绑定到字段。只有Properties

    改变你的班级

    public class ABCClass 
    {
        public int A = 1;
        public int B = 2;
        public int C = 3;
    
        public override string ToString() 
        {
           return (A + B + C).ToString();
        }
    }
    

    为此:

    public class ABCClass 
    {
        public int A {get;set;}
        public int B {get;set;}
        public int C {get;set;}
    
        public override string ToString() 
        {
           return (A + B + C).ToString();
        }
    
        public ABCClass()
        {
            A = 1;
            B = 2;
            C = 3;
        }
    }
    

    顺便说一句,您应该在 XAML 中创建绑定,而不是过程代码。

    另外,请记住,如果您以后想要修改 A,B,C 的这些值,除非您充分地 Implement INotifyPropertyChanged,否则这些更改不会反映。

    请习惯 C# 符号,像这样放置“埃及大括号”:

    public class MyClass {
        //...Etc    
    }
    

    而不是正确的方式

     public class MyClass
     {
          //...Etc
     }
    

    让我想呕吐,因为与蹩脚的 java 东西相似。

    【讨论】:

      【解决方案2】:

      您似乎正试图让ABCClassToString 值显示在名为txtKeyTextBox 中。如果是这种情况,您根本不需要转换器,因为Binding 的默认行为是在非字符串对象绑定到字符串属性时使用ToString 值(TextBox.Text 在此案例)。

      虽然没有必要为您的 A,B,C 值使用属性来支持这种情况,但通常使用公共字段是不好的做法,因此您应该考虑将它们设为私有或使用属性包装它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-26
        • 2021-11-08
        • 2012-12-11
        • 1970-01-01
        • 2013-12-19
        • 1970-01-01
        • 2016-09-30
        相关资源
        最近更新 更多