C#WPF节点遍历?

时间:2011-07-21 20:27:42

标签: c# wpf

我有一个这样的按钮:

<Button Grid.Column="0" Margin="10">
    <Button.Content>
        <Viewbox>
            <Label Name="Option1">Hello</Label>
        </Viewbox>
    </Button.Content>
</Button>

我想得到它的内容(你好)。我以前用过

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

它给了我按钮的内容,如果它只是一些值,但现在有一个视图框和一个标签,所以它不起作用。我可以做一些事情(e.Source as Button).Content.Viewbox.Label.Content()?

3 个答案:

答案 0 :(得分:2)

你需要这样做:

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

但它应该仍然有用。

另请注意,由于您使用as关键字进行'安全投射',因此您可能会遇到null投掷NRE。所以你可能想要更加冗长,如:

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

   // .. etc
}

答案 1 :(得分:0)

您必须将Button.Content转换为Viewbox,然后将Viewbox.Content转换为Label,然后将Label.Content转换为字符串

答案 2 :(得分:0)

甚至不要尝试这样做......当然, 是可能的,但它很痛苦且容易出错。改为使用DataTemplate

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

呈现按钮内容的方式纯粹是UI关注点。逻辑内容应该(通常)与它的呈现方式无关。使用上面的代码,您可以直接通过Content属性检索逻辑内容。