gpt4 book ai didi

c# - 在 wpf 中显示用户控件的替代方法

转载 作者:行者123 更新时间:2023-11-30 21:04:52 24 4
gpt4 key购买 nike

我想知道是否有其他方法可以在 WPF 应用程序的 mainwindow 中显示 usercontrols。目前,我利用 usercontrols 的可见性属性在单击按钮时一次显示一个用户控件。我将用户控件的可见性设置为 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;
}

它不起作用。正确的做法是什么?

最佳答案

您可以有一个 ContentControl(在 MainWindow xaml 中),并将其内容绑定(bind)到一个 View ,以便您可以在代码中切换它。像这样:

<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");
}
}

关于c# - 在 wpf 中显示用户控件的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12054249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com