Wpf 动态生成的文本框和输入绑定:将命令放在何处
我正在ItemsControl中生成一个文本框列表,如下所示:Wpf 动态生成的文本框和输入绑定:将命令放在何处,wpf,binding,mvvm,command,Wpf,Binding,Mvvm,Command,我正在ItemsControl中生成一个文本框列表,如下所示: <ItemsControl ItemsSource="{Binding CurrentCandidate.Properties}"> <ItemsControl.ItemTemplate> <DataTemplate> <DockPanel> <TextBlock DockPanel.Dock="Top" Text="{Binding DisplayNa
<ItemsControl ItemsSource="{Binding CurrentCandidate.Properties}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{Binding DisplayName}" />
<Border DockPanel.Dock="Top">
<TextBox Text="{Binding Value, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Command="{?}" CommandParameter={?} Key="PgUp" />
<KeyBinding Command="{?}" CommandParameter={?} Key="Enter" />
</TextBox.InputBindings>
</TextBox>
</Border>
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在输入绑定中,我希望访问ViewModel级别上可用的命令,即与ItemsSource级别相同的命令。为了从ItemTemplate中访问它,到目前为止,我使用了以下解决方法:
<TextBlock x:Name="tbCurrentCandidate"
Tag="{Binding Path=CurrentCandidate}"
Visibility="Hidden"></TextBlock>
<TextBlock x:Name="tbReset"
Tag="{Binding Path=ResetInputCommand}"
Visibility="Hidden"></TextBlock>
<TextBlock x:Name="tbValidate"
Tag="{Binding Path=ValidateCommand}"
Visibility="Hidden"></TextBlock>
这是一个类似HTML隐藏字段的变通方法,用于访问在我需要的地方不可用的属性,但我想一定有更好的方法
任何能帮我的人:因为让那片痛苦变得不那么痛苦而感到被拥抱;-) 为什么不在基本视图模型类中使用父属性作为视图模型基础。然后在XAML中,您可以简单地绑定到Parent.TheCommand
public class ViewModelBase : INotifyPropertyChanged
{
/// <summary>
/// The model's parent item.
/// </summary>
protected ViewModelBase _parent;
/// <summary>
/// Default Constructor.
/// </summary>
/// <param name="parent">Optional Parameter, The model's parent model. </param>
public ViewModelBase(ViewModelBase parent = null)
{
_parent = parent;
}
/// <summary>
/// The model's parent model.
/// </summary>
public ViewModelBase Parent
{
get { return _parent; }
}
//All other common properties and methods.
}
公共类ViewModelBase:INotifyPropertyChanged
{
///
///模型的父项。
///
受保护的ViewModelBase\u父对象;
///
///默认构造函数。
///
///可选参数,模型的父模型。
公共ViewModelBase(ViewModelBase父级=null)
{
_父母=父母;
}
///
///模型的父模型。
///
公共ViewModelBase父对象
{
获取{return\u parent;}
}
//所有其他通用属性和方法。
}
因为XAML中的绑定是动态的,所以它不需要是父对象的具体类型
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=Name}
将
ItemsControl
替换为包含所需命令的DataContext
的父控件类型。是否尝试使用类似{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:type ItemsControl},Path=Name}
?将ItemsControl替换为具有包含所需命令的DataContext的父控件类型。是的,我发现这是一个有效的方法:{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:type UserControl},Path=DataContext.ResetInputCommand}。它不是很漂亮,但它可以工作,因为还没有其他响应:您可以将其发布为一个响应,因此我可以将其标记为应答谢谢您的提示,但我不打算通过创建导航属性来进一步扩大我的ViewModels。
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=Name}