【发布时间】:2022-01-18 17:19:42
【问题描述】:
我有一个定义为依赖属性的字符串列表。我通过 xaml 分配列表项的值。我可以分配文字字符串值,但我不知道如何将这些值绑定到 viewmodel 中的数据。
public static readonly DependencyProperty StringArgsProperty = DependencyProperty.Register(
"StringArgs", typeof(List<string>), typeof(GameTextBlock), new FrameworkPropertyMetadata(new List<string>()));
public List<string> StringArgs
{
get { return (List<string>)GetValue(StringArgsProperty); }
set { SetValue(StringArgsProperty, value); }
}
以下是我目前如何将项目绑定到所述列表:
<common:GameTextBlock.StringArgs>
<sys:String>arg1</sys:String>
<sys:String>arg2</sys:String>
</common:GameTextBlock.StringArgs>
我想要做的是将 arg1/arg2 替换为 ViewModel 中的值。如果我没有分配给列表的项目,我可以执行“{Binding NameOfField}”。
我不想在 ViewModel 中创建整个列表并绑定列表,因为我希望能够仅使用 xaml 来挑选项目。这可以实现吗?
编辑:我想要实现的更清晰的示例:
public class ViewModel
{
public string Item1 {get; set;}
public string Item2 {get; set;}
public string Item3 {get; set;}
}
然后我希望能够在一个包含多个 GameTextBlock 的 xaml 中使用它们,如下所示:
<GameTextBlock x:Name = "txt1" >
<GameTextBlock.StringArgs>
<sys:String>{Binding VMItem1}</sys:String>
<sys:String>{Binding VMItem3}</sys:String>
</GameTextBlock.StringArgs>
</GameTextBlock>
<GameTextBlock x:Name = "txt2" >
<GameTextBlock.StringArgs>
<sys:String>{Binding VMItem1}</sys:String>
<sys:String>{Binding VMItem2}</sys:String>
</GameTextBlock.StringArgs>
</GameTextBlock>
<GameTextBlock x:Name = "txt3" >
<GameTextBlock.StringArgs>
<sys:String>{Binding VMItem1}</sys:String>
</GameTextBlock.StringArgs>
</GameTextBlock>
【问题讨论】:
-
不要使用
new FrameworkPropertyMetadata(new List<string>())。对于 GameTextBlock 的所有实例,它将是相同的列表。使用new FrameworkPropertyMetadata(null)并在构造函数中初始化StringArgs -
最好在构造函数中通过
SetCurrentValue(StringArgsProperty, new List<string>())来实现。 -
@user2396632:从哪里“挑选”什么项目?所有项目都应在视图模型中定义。
-
@mm8 视图模型中定义的项目。我可以通过在 GameTextBlock 中创建属性“Arg0、Arg1、Arg2...”然后像
一样分配它们来实现这一点。为每个 GameTextBlock 和绑定创建一个 List 对我来说效果不佳,因为有多个 GameTextBlock 重用相同的单个 Args,所以我真的想要一种在 xaml 中创建列表的方法,但绑定单个项目的值. -
那么您想将视图模型中的项目与您在 XAML 中指定的项目结合起来吗?