开发者

C# WPF node traversing?

I have a button like this:

<Button Grid.Column="0" Margin="10">
    <Button.Content>
        <Viewbox>
            <Label Name="Option1">Hello</L开发者_开发技巧abel>
        </Viewbox>
    </Button.Content>
</Button>

And I want to get it's content (Hello). I have previously used

 (e.Source as Button).Content.ToString()

And it gave me the content of the button if it was only some value, but now there's a viewbox and a label so it doesn't work. Can I do something like (e.Source as Button).Content.Viewbox.Label.Content() ?


You would need to do it like:

(((e.Source as Button).Content as Viewbox).Child as Label).Content

But it should still work.

Also note that since you're using 'safe casting' with the as keyword, at any point you could run into a null which would throw an NRE. So you might want to be a bit more verbose like:

Button b = e.Source as Button;
if(b != null) {
   Viewbox v = b.Content as Viewbox;

   // .. etc
}


You will have to cast Button.Content as Viewbox, then Viewbox.Content as Label, then cast the Label.Content to a string


Don't even try to do it like that... Sure, it is possible, but it's painful and error-prone. Use a DataTemplate instead:

<Button Grid.Column="0" Margin="10" Content="Hello">
    <Button.ContentTemplate>
        <DataTemplate>
            <Viewbox>
                <ContentPresenter Content="{Binding}" />
            </Viewbox>
        </DataTemplate>
    </Button.ContentTemplate>
</Button>

The way the button content is presented is purely a UI concern. The logical content should (usually) be unrelated to how it's presented. With the code above, you can retrieve the logical content directly through the Content property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜