سؤال

I have a WPF Expander, such as this:

    <Expander Canvas.Left="251" Canvas.Top="425" Header="expander1" Height="100" Name="expander1">
        <Grid>
            <StackPanel Margin="10,4,0,0">
                <CheckBox Margin="4" Content="Option 1" Checked="chk_DoThis" />
                <CheckBox Margin="4" Content="Option 2" Checked="chk_DoThis" />
                <CheckBox Margin="4" Content="Option 3" Checked="chk_DoThis" />
            </StackPanel>
        </Grid>
    </Expander>

When a checkbox is clicked, I fire off a 'Checked' event.

Is there some way to pull out a string that contains the 'Header' of the Expander? In this example, I want to pull out 'expander1' and assign that to a string.

I tried a few ways of doing this and couldn't get it to work. I have done this same concept using TreeViewItems and using a Header.Parent.ToString() to get what I wanted. No luck here. This is what I'm referring to:

    string child = ((TreeViewItem)((TreeViewItem)((TreeView)sender).SelectedItem)).Header.ToString();

Does anyone know of a way I could do this for my Expander example. Googling and searching this site has yielded no return. It's probably something easy and I'm just overlooking it.

Thanks to anyone that has some ideas.

هل كانت مفيدة؟

المحلول

You can easily get the Expander from the CheckBox. Just iterate to the VisualTree and get the Top most parent's Expander. I just simply did only one parent in the below example.

void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Expander expander = (Expander)checkBox.Parent;

            if (expander != null)
            {
                string str = expander.Header.ToString();
                Debug.WriteLine(str);
            }
        }

I hope it will help you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top