简体   繁体   中英

Avalonia UI - How to get/set properties of UI controls from code

I have several TabControl s defined in my XAML. I would like my ViewModel to be aware of the TabItem name or the index of the TabItem that is selected.

I also have a ScrollViewer that i would like to always scroll to the bottom when ever a button is pressed.

I should be able to solve both of the above issues if i could somehow get access to the elements in my code.

How can i acheve something like this:

var tabIndex = this.GetElement<TabControl>("NameOfSomeTabControl").SelectedIndex;

var scrollViewer = this.GetElement<ScrollViewer>("NameOfSomeScrollViewer");
scrollViewer.VerticalScrollBarValue = scrollViewer.VerticalScrollBarMaximum;

Edit: code for xaml , viewModel code

Edit 2: Looks like i am able to get the instance of the element from the window class , however i'm still not sure how to pass the reference to the ViewModel.

Edit 3: I can achieve the scroll viewer going to the bottom automatically using the code below. however, once that method is invoked it seems like the scrolling gets disabled.

var tbRaw = this.Get<TextBlock>("tbRawOutput");
tbRaw.PropertyChanged += (s,e) => {
    var svRaw = this.Get<ScrollViewer>("svRawOutput");
    svRaw.Offset = new Vector(svRaw.Offset.X, svRaw.Extent.Height -svRaw.Viewport.Height);};

An easier way to do this might be to use the DataContextChanged event handler in your main Window class:

public MainWindow()
{
    InitializeComponent();
    DataContextChanged += (object sender, EventArgs wat) =>
    {
        // here, this.DataContext will be your MainWindowViewModel
    };
}

Then you can attach more event handlers/use getters and setters on the view model from the Window

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