Change snap when focus changes

I have an application that has several tree views and one propertygrid (from the advanced WPF toolkit). The goal is to display the properties of the selected item. I am new to WPF, so I started from a single tree and linked an objectsgrids object like this

<xctk:PropertyGrid x:Name="xctkPropertyGrid"
                       Grid.Column="2"
                       ShowSearchBox="False"
                       ShowSortOptions="False"
                       SelectedObject="{Binding ElementName=actionsTreeView, Path=SelectedItem, Mode=OneWay}">
</xctk:PropertyGrid>

It seems to be working fine. But it is always connected with actionsTreeView. I really need to update this property attribute when the focus changes to another one selected in another tree. I achieved my goal using SelectedItemChangedeach tree image and setting the grids selectedobject property like this. Is this possible with data binding and triggers. My solution adds some code and a tight connection, and this is not very similar to MVVM.

Regards, Jeff

+4
source share
1 answer

Ok, here is how I decided to solve my problem:

Each treeview is bound to a viemodel property on the main model. I also created a property SelectedItemon the main view model like this, which is tied with the property: SelectedObject:

private object selectedItem;
public object SelectedItem
{
    get { return selectedItem; }
    set
    {
        selectedItem = value;
        OnPropertyChanged("SelectedItem");
    }
}

Then I add behavior to each tree view that updates this one SelectedItem:

public class UpdateSelectedItemBehavior : Behavior<TreeView>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        this.AssociatedObject.GotFocus += AssociatedObject_GotFocus;
        this.AssociatedObject.SelectedItemChanged += AssociatedObject_SelectedItemChanged;
    }

    void AssociatedObject_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        ViewModels.MainViewModel mainViewModel = AssociatedObject.DataContext as ViewModels.MainViewModel;
        if (mainViewModel != null)
        {
            mainViewModel.SelectedItem = AssociatedObject.SelectedItem;
        }
    }

    void AssociatedObject_GotFocus(object sender, RoutedEventArgs e)
    {
        ViewModels.MainViewModel mainViewModel = AssociatedObject.DataContext as ViewModels.MainViewModel;
        if (mainViewModel != null)
        {
            mainViewModel.SelectedItem = AssociatedObject.SelectedItem;
        }
    }
}
+1
source

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


All Articles