问题
I am very new to WPF and this is my 1st application.
I have a Ribbon with different buttons. I want to load a UserControl based on which button is clicked.
I have a button called "Change Password" and I created the UserControl that will represent the UI to change the password.
I have another button called "Unlock Account" and I have a UserControl that can unlock an account.
App --> Ribbon --> RibbonButton --> SwappableUserControlAtRunTime
I want to use the same space in my Window to load/unload UserControls based on whats clicked.
I am using WPF 4.5 and .Net 4.5 on Windows 8.1 I am targeting PC's with .Net 4.5 and Windows 7+
回答1:
You can load the UserControls in the ContentControl. Refer below code.
<RibbonWindow x:Class="LayoutWPF_Learning.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Ribbon Grid.Row="0">
<RibbonTab Header="Load UC">
<StackPanel Orientation="Horizontal">
<Button Content="UserControl1" Click="Button_Click"/>
<Button Content="UserControl2" Click="Button_Click_1"/>
</StackPanel>
</RibbonTab>
</Ribbon>
<ContentControl Grid.Row="1" x:Name="cntCtrl" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"/>
</Grid>
public partial class MainWindow : RibbonWindow
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
cntCtrl.Content = new UserControl1();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
cntCtrl.Content = new UserControl2();
}
}
回答2:
Even though you're going with codebehind (I'd recommend you look into MVVM) you'll be able to use a Converter to do this, this is more the WPF way of working than altering controls at runtime from your C# code.
There'll be loads of examples of how to use converters; Google "WPF Converter". Here's one that's relevant to your requirement: http://www.codeproject.com/Tips/285358/All-purpose-Boolean-to-Visibility-Converter
来源:https://stackoverflow.com/questions/29952693/wpf-usercontrol-loading-dynamically-based-on-which-button-is-clicked