我创建了一个ListViewTemplate
作为UserControl
,当我点击这个汉堡Button
时,我想显示它,这是我的代码:
Main.xaml
:
<SplitView.Content >
<Grid Background="White" >
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#f0f0f0" >
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="TrieButton" Margin="0" Content=""
Width="50" Background="Transparent" VerticalAlignment="Stretch" Click="TrieButton_Click" />
</StackPanel>
</Grid>
<Frame Grid.Row="1" x:Name="ContentFrame" Margin="0" />
</Grid>
</SplitView.Content>
这是代码Behind:
Main.xaml.cs
:
private void TrieButton_Click(object sender, RoutedEventArgs e)
{
ListViewTemplate c = new ListViewTemplate();
if (c.Visibility == Visibility.Visible)
{
c.Visibility = Visibility.Collapsed;
}
else
{
c.Visibility = Visibility.Visible;
}
}
这是我的UserControl
:
ListViewTemplate.xaml
:
<Grid x:Name="FilterGrid" Background="Black">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0" >
<ListView x:Name="Liste" Background="Black" >
<ListViewItem >
<TextBlock Text="Nom" Foreground="#9d9e9e"/>
</ListViewItem>
<ListViewItem >
<TextBlock Text="Catégorie" Foreground="#9d9e9e"/>
</ListViewItem >
</ListView>
</StackPanel>
</Grid>
我的问题是当我点击ListView
时,UserControl
TrieButton
没有显示,即使我增加了Grid
的高度
所以,我如何更正我的代码,以便在点击Listview
时显示TrieButton
感谢您的帮助
答案 0 :(得分:1)
响应按钮单击,您错误地创建了ListViewTemplate对象的新实例,然后将其丢弃。
我认为你真正想做的事情就是这样:
private void TrieButton_Click(object sender, RoutedEventArgs e)
{
ListViewTemplate c = (ListViewTemplate) Controls["Liste"];
if (c.Visibility == Visibility.Visible)
c.Visibility = Visibility.Collapsed;
else
c.Visibility = Visibility.Visible;
}
这里我们检索现有的Control并更改其可见/折叠状态。
答案 1 :(得分:1)
首先:您没有在任何地方将UserControl
添加到主XAML。您应该首先添加到XAML:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:usercontrol="clr-namespace:WpfApplication1"
然后:
<Grid Background="White" x:Name="MGrid">
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="10" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#f0f0f0" >
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="TrieButton" Margin="0" Content=""
Width="50" Background="Transparent" VerticalAlignment="Stretch" Click="TrieButton_Click" />
</StackPanel>
</Grid>
<Frame Grid.Row="1" x:Name="ContentFrame" Margin="0" />
<usercontrol:ListViewTemplate x:Name="c" Grid.Row="2" Visibility="Collapsed"></usercontrol:ListViewTemplate>
</Grid>
其次:您刚刚创建了ListViewTemplate
的新实例。您应该使用FindName
方法找到放置在XAML中的方法,然后像这样更改Visibility
:
private void TrieButton_Click(object sender, RoutedEventArgs e)
{
ListViewTemplate c = MGrid.FindName("c") as ListViewTemplate;
c.Visibility = c.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}