【问题标题】:How to get value from Binding object in Code as a string (WPF)如何从代码中的绑定对象获取值作为字符串(WPF)
【发布时间】:2018-05-22 19:58:39
【问题描述】:

我想在我的代码中从 Binding 中获取值并将其用作字符串。我该怎么做?

Binding b = new Binding("MyProperty")
                {
                    Source = myobject
                };
//[...]
string value = b //HOW TO GET VALUE FROM b ?

顺便说一句: 我希望在检索此值时调用附加到 Binding 的转换器。

【问题讨论】:

  • 我不确定我是否理解你的问题,但我的目标只是获得价值,因为它是由“b”绑定的
  • 如果我有 我want to get string result = //Smith - 777 必须有一个选项来获取 Binding / Multibinding 以提取绑定它的内容,对吧?
  • 如果您尝试使用绑定来获取myobject.MyPopertyhave a look at these answers 的值。如果你能用英语清楚明确地说明你想要获得什么价值,这个问题将会大大改善。

标签: wpf string data-binding multibinding valueconverter


【解决方案1】:

我发现解决方案可能是一个带有 DependencyProperty 的辅助类。

辅助类

public class TestClass : FrameworkElement
{
    public string MyProperty
    {
        get { return (string)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }
    public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(TestClass), new PropertyMetadata(""));
}

绑定转换为字符串

Binding b = new Binding("MyProperty") { Source = myobject };
TestClass tc = new TestClass { DataContext = b };
BindingOperations.SetBinding(tc, TestClass.MyPropertyProperty, b);
string txt = tc.MyProperty;

优点:

  • 您可以使用绑定和多重绑定
  • 您可以使用转换器

缺点:

  • 每次我们创建一个继承自FrameworkElement的类,这意味着我们做了一些不必要的操作。

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 2023-01-16
    相关资源
    最近更新 更多