WPF - binding in XAML to an object created in code

Is it possible to use an object created in the code (for example, C #) for binding in XAML?

For example:

public class MyForm
{
    private MyComplexObject complexObject;

    public MyForm()
    {
        InitializeComponent();
    }

    public OnButtonClick(object sender, RoutedEventArgs e)
    {
        complexObject = new MyComplexObject();
    }
}

complexObjectnot created until a button is clicked. But as soon as this button is pressed, I would like to have a text field that is tied to complexObject.IDstarting to show the identifier.

I would like to do this in XAML, if possible.

Can this be done? If so, how?

+3
source share
2 answers

, XAML . complexObject.ID, complexObject!= Null. - " ", 0 ( ). , complexObject.ID, complexObject, , null.

public int ID
{
    get
    {
        if (complexObject != null)
            return complexObject.ID;
        return 0; // or null or some appropriate default
    }
    set
    {
        if (complexObject != null)
            complexObject.ID = value;
    }
}
+2

, , , . MVVM (Model-View-ViewModel), WPF. : MVVM

MMVM, , ViewModel. DataContext . , , . , Id og ComplexObject. ViewModel ComplexObject, , , :

<TextBlock Text="{Binding ComplexObject.ID}" /> 

ComplexObject , . , ViewModel ( , ComplexObject, View, . , ComplexObject a DependencyProperty , , INotifyPropertyChanged - PropertyChanged . .

+9

Source: https://habr.com/ru/post/1724443/


All Articles