我想知道是否有另一种方法可以在WPF应用程序中usercontrols
内显示mainwindow
。
目前,我使用usercontrols
的visibility属性在按钮单击时一次显示一个usercontrol。我将用户控件的可见性设置为Hidden
,按钮点击时我更改了可见性。它完美地运作。但这是正确的方法吗?
编辑:
我试过这样的事情,但它不起作用。
mainwindow.xaml:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="54*" />
<RowDefinition Height="257*" />
</Grid.RowDefinitions>
<Grid Grid.Row="1">
<ContentControl Content="{Binding CurrentView}"/>
</Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="25,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<Button Content="Button" Height="23" HorizontalAlignment="Right" Margin="0,12,251,0" Name="button2" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>
有两个用户控件,即UserControl1和UserControl2。在后面的代码中:
private UserControl currentview;
private UserControl CurrentView
{
get
{
return this.currentview;
}
set
{
this.currentview = value;
//RaisePropertyChanged("CurrentView");
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
UserControl1 uc1 = new UserControl1();
CurrentView = uc1;
}
它不起作用。什么是正确的方法?
答案 0 :(得分:4)
您可以拥有ContentControl
(在MainWindow xaml中),并将其内容绑定到视图,以便您可以在代码中切换它。像这样:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="54*" />
<RowDefinition Height="257*" />
</Grid.RowDefinitions>
<ContentControl Grid.Row="0" Content="{Binding CurrentView}"/>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="25,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<Button Content="Button" Height="23" HorizontalAlignment="Right" Margin="0,12,251,0" Name="button2" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>
在背后的代码中:
private UserControl currentView;
public UserControl CurrentView
{
get
{
return this.currentView;
}
set
{
if (this.currentView == value)
{
return;
}
this.currentView = value;
RaisePropertyChanged("CurrentView");
}
}
答案 1 :(得分:0)
我觉得它没有什么问题,如果你可以控制你的窗口生命周期内的内存。此外,Amadeus Hein的回答。