WPF 自定义控件,在ViewModel里面获取自定义控件的值

本文介绍如何在用户自定义的XAML中编写代码,并展示了控件的定义及使用方式。通过双向绑定机制,可以轻松获取用户选择的城市信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上图:

用户自定义CS里面代码如下:

自定义控件XAML里面的代码如下:

调用用户自定义控件的页面代码如下:

CItySelected的属性值就是我们点击确定按钮以后得到的值,通过双向绑定在VIewModel里面取到值就可以了

转载于:https://www.cnblogs.com/lijin/p/3392983.html

WPF中,如果你想在一个自定义控件里封装并传递Command委托给用户,通常会使用` ICommand`接口,它是命令模式的一个实现,用于管理UI中的可操作行为。以下是如何在自定义控件中实现Command传递的步骤: 1. 定义Command: 首先,在你的自定义控件ViewModel中创建一个`ICommand`实例,如`RoutedCommand`或使用`System.Windows.Input.ICommand`。例如,可以创建一个`MyCustomControlViewModel`: ```csharp using System.Windows.Input; public class MyCustomControlViewModel { private RoutedCommand _myCommand; public MyCustomControlViewModel() { _myCommand = new RoutedCommand(); _myCommand.Executed += MyCommand_Executed; } public ICommand MyCommand { get { return _myCommand; } } private void MyCommand_Executed(object sender, EventArgs e) { // 这里是你想要执行的具体操作 } } ``` 2. 在控件中绑定Command: 在XAML中,将你的自定义控件的数据模板(DataTemplate或UserControl)设置为绑定到`MyCommand`。例如: ```xml <UserControl x:Class="YourNamespace.MyCustomControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:i="http://schemas.microsoft.com/expression/blend/2008" 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="400"> <UserControl.Command> <i:Interaction.Triggers> <i:EventTrigger EventName="ButtonClicked"> <i:InvokeCommandAction Command="{Binding Path=DataContext.MyCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"/> </i:EventTrigger> </i:Interaction.Triggers> <!-- 其他控件内容 --> </UserControl> ``` 在这个例子中,`ButtonClicked`是你的按钮或者其他响应点击的元素的事件,它会在用户点击时调用`MyCommand`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值