WPF——在ItemControl的ItemTemplate中绑定ViewModel的属性

在为 ItemControl 编写 ItemTemplate 时候,需要使用到 UserControlDataContext,即与绑定集合同等地位的属性,例如下述代码:

<ListBox ItemsSource="{Binding Collections}">
	<ListBox.ItemTemplate>
		<DataTemplate>
			<UniformGrid Columns="2">
				<TextBlock Text="{Binding Name}" />
				<ComboBox ItemsSource="{Binding ?}" SelectedValue="{Binding Type}" />
			</UniformGrid>
		</DataTemplate>
	</ListBox.ItemTemplate>
</ListBox>

注意到在 ListBox 的绑定中,由于 ItemTemplate 默认绑定到了集合的单个对象,因此无法采用直接的方式绑定到 UserControlDataContext 中的属性,即对应的 ViewModel.OtherCollections

因此,使用 FindAncestor 的绑定方式,通过获取 UserControlDataContext ,继而间接绑定到 ViewModel 中的集合,ComboBox 的绑定代码如下:

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=UserControl},
	Path=DataContext.OtherCollections}" SelectedValue="{Binding Type}" />

其中 ViewModel.cs 相关代码如下:

Class ViewModel : ViewModelBase
{
	// Other Definitions
	//...
	private ObservableCollection<Foo> _collections;
	public ObservableCollection<Foo> Collections
	{
		get => _collections;
		Set => Set(ref _collections, value);
	}
	public List<Bar> OtherCollections => new List<Bar>();
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在MVVM模式下,PassWordBox的密码不能直接ViewModel属性,因为密码是敏感信息,不应该以明文形式存储在内存。因此,我们需要使用PasswordBox的SecureString属性来存储密码,并在ViewModel创建一个SecureString类型的属性来接收密码。 首先,在XAML,我们需要将PassWordBox的PasswordChanged事件与Command,以便在密码发生变化时触发Command执行。例如: ``` <PasswordBox PasswordChanged="{Binding PasswordChangedCommand}" /> ``` 然后,在ViewModel,我们需要创建一个SecureString类型的属性来接收密码,并创建一个Command来处理密码变化事件,例如: ``` public class LoginViewModel : INotifyPropertyChanged { private SecureString _securePassword; public SecureString SecurePassword { get { return _securePassword; } set { _securePassword = value; OnPropertyChanged(nameof(SecurePassword)); } } public ICommand PasswordChangedCommand => new RelayCommand<PasswordBox>((pb) => { SecurePassword = pb.SecurePassword; }); // INotifyPropertyChanged implementation... } ``` 在这个示例,我们创建了一个SecurePassword属性来接收密码,并使用PasswordBox的SecurePassword属性将密码赋值给SecurePassword。我们还创建了一个PasswordChangedCommand来处理密码变化事件,该Command使用RelayCommand实现,并将PasswordBox作为参数传递。当密码发生变化时,Command会将SecurePassword属性设置为新密码。 需要注意的是,由于SecureString无法直接转换为字符串,因此我们需要在处理密码时使用相应的方法来转换或处理SecureString。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值