(WPF) How can I find ancestor about two ItemsControl in code behind?

424 views Asked by At

I have a ItemsControl(A). ItemSourece is a Class "Account".It contains some controls and another ItemsControl(B).

ItemsControl(B) includes some CheckBox. It's ItemSourece is ObservableCollection included in Class "Account". CheckBox's Content is binding to Content. CheckBox's IsChecked is bindind to IsChecked.

enter image description here

Now when I click CheckBox, I want to get ID and User in Class "Account", but I don't know hot to get them. I already try to use

    private void CheckBox_Click(object sender, RoutedEventArgs e)
    {
        CheckBox checkBox = sender as CheckBox;
        var parentElement = (ContentPresenter)VisualTreeHelper.GetParent(checkBox);           
    }

but it still can't get parent. Althouth runtime can show parentElement.VisualParent, but actually it is not work. enter image description here enter image description here

Please help me! Thanks!

1

There are 1 answers

4
Mike On BEST ANSWER

@RickyChen - I see your problem. AuthorityCheckBox binds to your visual checkboxes. When you click on a checkbox, there isn't any link back to the AuthorityCheckBox.

What you can do is abuse the Tag property of your checkbox and place the AuthorityCheckBox reference there.

Adjust your your AuthorityCheckBox class so it contains public Account Parent that is assigned in the constructor. This way you can easily get the AuthorityCheckBox parent:

public class AuthorityCheckBox
{
    public string Content { get; set; }
    public bool IsChecked { get; set; }
    public bool IsEnabled { get; set; }
    public Account Parent { get; private set; }

    public AuthorirtyCheckBox(Account parent)
    {
         this.Parent = parent;
    }
}

The event handler then looks like this:

private void CheckBox_Click(object sender, RoutedEventArgs e)
{
    AuthorityCheckBox acb = (sender as FrameworkElement).Tag as AuthorityCheckBox;
    Account parent = acb.Parent;           
}