0

I'd like to get value from Binding in my code and use it as a string. How Can I do that?

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

BTW: I would like the Converter attached to Binding to be called when retrieving this value.

gmik
  • 31
  • 5
  • I am not sure if I understand your question well, but my goal is only to get value as it is Binded by "b" – gmik May 21 '18 at 12:41
  • What if i have and I want to get string result = //Smith - 777 There must be an option to get Binding / Multibinding to extract what binds it to, right? – gmik May 21 '18 at 12:46
  • If you're trying to use the binding to get the value of `myobject.MyPoperty`, [have a look at these answers](https://stackoverflow.com/questions/3577802/wpf-getting-a-property-value-from-a-binding-path). This question would be much improved if you would state, clearly and unambiguously, in English, what value you want to get. – 15ee8f99-57ff-4f92-890c-b56153 May 21 '18 at 13:55

1 Answers1

0

I found that the solution could be an auxiliary class with DependencyProperty.

Auxiliary class

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 conversion to String

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

Advantages:

  • You can use Binding and MultiBinding
  • You can use Converters

Disadvantages:

  • Each time we create a class that inherits from the FrameworkElement, which means that we do unnecessary operations.
gmik
  • 31
  • 5