【发布时间】:2015-04-13 04:19:57
【问题描述】:
我有MainWindow.xaml 有ContentControl。
我创建了 4 个UserControls。
当按下我的UserControl 内的按钮时,我想在MainWindow.xaml 中更改ContentControl 的内容。
这是我的MainWindow.xaml:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:KIOSK" mc:Ignorable="d" x:Class="KIOSK.MainWindow"
Title="MainWindow" Height="350" Width="525" WindowState="Maximized">
<ContentControl Name="contentMain">
<local:main_screen />
</ContentControl>
</Window>
这里是我的用户控件:
1)main_screen.xaml
<UserControl x:Class="KIOSK.main_screen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Name="grid1" ShowGridLines="True">
<Button Margin="10" Background="#FFA4F200" Click="Button_Click"/>
</Grid>
</UserControl>
2) ClubRules.xaml
<UserControl x:Class="KIOSK.ClubRules"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" Background="White">
<Grid ShowGridLines="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" x:Name="grid1">
<Button Margin="0,15,0,15" Background="#FFFE0555" HorizontalAlignment="Center" Click="Button_Click" />
</Grid>
</UserControl>
在 main_creen.xaml.cs 内部我为按下按钮而写:
ClubRules cr = new ClubRules();
MainWindow mw = new MainWindow();
mw.contentMain.Content = new ClubRules();
但它不起作用.. 我想在按下按钮时更改 UserControl 内的 ContentControl 的内容。
【问题讨论】:
-
您创建的 MainWindow 的实例是否正在显示给用户?
-
@bit,我不太明白你的意思。但用户看到 MainWindow.xaml 并且我想更改(导航他)ContentControl 的内容。我更改了用户控件。
-
您似乎使用了新创建的 MainWindow() 实例,而不是尝试 contentMain.Content = new ClubRules();直接..
-
@bit,如您所见,UserControl 内部的按钮。你能给我举个例子吗?
-
问题是显示了 MainWindow 的一个实例,以及您在按钮按下事件中创建的另一个实例。您正在将 ClubRules 分配给后者。您必须想办法获取已透析的 MainWindow 的引用并将 ClubRules 分配给它
标签: c# wpf xaml user-controls