简体   繁体   中英

How to access a control that is created in a separate class file, in xaml view?

I created I dynamic label in .CS (FormEvents.cs)

        DXTabItem myTabItem= new DXTabItem();
        myTabItem.Header = new Label()
        { 
            Name= "lblTabAccountHeader", 
            Content = "MyTab" + Convert.ToString(UserID) 
        };

and I want to access the label "lblTabAccountHeader" in my (AccountsDisplay.xaml) and use it as binding ElementName in placement target

<Popup x:Name="ClosingMenuPopMenuControl"  PlacementTarget="{Binding ElementName=lblTabAccountHeader}" StaysOpen="False" PopupAnimation="Fade">

You can't directly access a label in xaml from a cs file. But it is possible if you implement the interface INotifyPropertyChanged and fire the event PropertyChanged when the corresponding property changes. You could achieve it with a string property.

FormEvents.cs

public class FormEvents : BindableBase
{
   private string someName;
    public string SomeName
    {
        get {return someName;}
        set { SetProperty(ref someName, value);}
    }

    public FormEvents()
    {
        DXTabItem myTabItem= new DXTabItem();
        myTabItem.Header = new Label()
        { 
            Name= "lblTabAccountHeader", 
            Content = "MyTab" + Convert.ToString(UserID) 
        };
        SomeName = lblTabAccountHeader.Content;
    }
}

In YouView.xaml.cs

public class YourView 
{
    prvate FormEvents instance = new FormEvents();

    public YourView()
    {
        instance.SomeName.PropertyChanged += EventHandler;

    }

    private void EventHandler(object obj)
    {
        TextBoxinYourView.Text = instance.SomeName;
    }
}

Thus when the property changes in your class file, it will be reflected in your view also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM