[英]How to write to HKEY_CURRENT_USER\\Control Panel\\Desktop\\WindowMetrics from WinUI3 C# app
[英]WinUI 3 - How to open a control in a page upon click of button from a User Control c#?
我在页面的 XAML 代码中有一个 ItemsRepeater,它的 ItemsSource 属性绑定到用户控件 (ObersvableCollection) 列表,这是我制作的自定义控件。 在这个用户控件中有一个按钮,我希望它可以打开我在页面的 Xaml 代码中设置的 SplitView 窗格。 我想我需要在点击事件的用户控件代码中获取页面的实例,但我不知道如何。
你可以这样做。
TestUserControl.xaml.cs
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System.Windows.Input;
namespace WinUI3App1;
public sealed partial class TestUserControl : UserControl
{
public static readonly DependencyProperty ClickCommandProperty = DependencyProperty.Register(
nameof(ClickCommand),
typeof(ICommand),
typeof(TestUserControl),
new PropertyMetadata(null));
public TestUserControl()
{
InitializeComponent();
}
public ICommand ClickCommand
{
get => (ICommand)GetValue(ClickCommandProperty);
set => SetValue(ClickCommandProperty, value);
}
}
测试使用控制.xaml
<UserControl
x:Class="WinUI3App1.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="ThisControl">
<StackPanel Orientation="Horizontal">
<Button Command="{x:Bind ClickCommand}" CommandParameter="{Binding ElementName=ThisControl}" Content="Click" />
</StackPanel>
</UserControl>
主窗口.xaml.cs
using CommunityToolkit.Mvvm.Input;
using Microsoft.UI.Xaml;
using System.Collections.ObjectModel;
using System.Windows.Input;
namespace WinUI3App1;
public sealed partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Install the CommunityToolkit.Mvvm NuGet package
// to avoid implementing commands yourself.
ClickCommand = new RelayCommand<TestUserControl>(OnClick);
for (int i = 0; i < 10; i++)
{
TestUserControls.Add(new TestUserControl()
{
ClickCommand = ClickCommand
});
}
}
public ObservableCollection<TestUserControl> TestUserControls { get; set; } = new();
public ICommand ClickCommand { get; set; }
private void OnClick(TestUserControl? sender)
{
SplitViewControl.IsPaneOpen = true;
}
}
主窗口.xaml
<Window
x:Class="WinUI3App1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<SplitView x:Name="SplitViewControl">
<SplitView.Pane>
<Grid/>
</SplitView.Pane>
<StackPanel Orientation="Vertical">
<ItemsRepeater ItemsSource="{x:Bind TestUserControls}" />
</StackPanel>
</SplitView>
</Window>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.