I have a question of how I can use the visual tree helper to get an object 开发者_如何转开发that I need. I have a user controll called DialogItemControll that I call from my main page like this:
DialogItemControll ivDialogWindow = new DialogItemControll()
ivDialogWindow.ivSave.Click += new RoutedEventHandler(ivSave_Click);
ivDialogWindow.Show();
And then I have the method ivSave_Click that gets called when I click the save button on my user controll. That method looks like:
void ivSave_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var firstStack = button.Parent as StackPanel;
var secondStack = firstStack.Parent as StackPanel;
TextBox te = secondStack.FindName("ivUserComment") as TextBox;}
This is where you can see my attempts to use the get parent and so on. Not so nicely done. So what I want is to get the whole object like:
var controll = ?? as DialogItemControll
My DialogItemControll looks like this :
<C1:C1Window x:Class="DialogItemControll"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:C1="clr-namespace:C1.Silverlight;assembly=C1.Silverlight"
mc:Ignorable="d"
d:DesignHeight="418" d:DesignWidth="401">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="5,5,5,5">
<TextBlock Name="ivHelpComment" FontSize="18">test</TextBlock>
<TextBox Name="ivUserComment" BorderThickness="2,2,2,2" Height="170"></TextBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" >
<Button Name="ivSave" HorizontalAlignment="Right" Height="22" Width="70" Margin="0,10,20,0" Click="ivSave_Click">Spara</Button>
<Button Name="ivCancel" HorizontalAlignment="Right" Height="22" Width="70" Margin="0,10,20,0" Click="ivCancel_Click">Avbryt</Button>
</StackPanel>
</StackPanel>
</Grid>
C1 window is the same as user control, its just a third party control. Please help me with how I should use the tree helper in a good way to get the whole object.
Thanks
You should try Linq To VisualTree:
http://www.scottlogic.co.uk/blog/colin/2010/03/linq-to-visual-tree/
This allows you to query the visual tree using a Linq style API (It is actually very similar to Linq to XML). In your example, you want to find a Descendant of a specific type. You can do this as follows:
var dialogItemControl = button.Descendants<DialogItemControll>()
.Cast<DialogItemControll>()
.Single();
The first part of the query finds all descendants of the queried element of a given type (you can also use Linq to VisualTree to find children, peers etc...), the second part casts the returned list to the given type, finally because we know there is only one descendant of the given type, we can use Single() to extract the single item.
Hope that helps.
精彩评论