c# - MVVM 绑定到数组索引
问题描述
我正在使用 MVVM,并且正在尝试绑定数组索引。XAML 控件的数据上下文绑定到视图模型。当我实例化控件时,我将数组索引发送到构造函数,然后将该索引分配给窗口资源,以便 XAML 可以直接使用它。该值按预期传递给构造函数,我可以在 XAML 页面的其他区域使用它,但由于某种原因,它不能用作数组索引。有谁知道这里发生了什么?
C#:
public partial class MyControl : UserControl {
public MyControl(int index) {
MyIndex = index;
InitializeComponent();
}
private int myIndex;
public int MyIndex {
get { return myIndex; }
set { myIndex = value; }
}
private void Mygrid_OnLoaded(object sender, System.Windows.RoutedEventArgs e) {
Resources["myResourceKey"] = MyIndex;
}
}
这是xaml:
定义资源:
<UserControl.Resources>
<sys:Int32 x:Key="myResourceKey"></sys:Int32>
</UserControl.Resources>
这不起作用。我收到绑定错误,因为它无法识别索引
<GradientStop Color="{Binding MyObservableCollection[DynamicResource myResourceKey].ColorsBo.PageBackgroundPrimary}" Offset="1"/>
这确实有效,因此资源值被传递到 xaml:
<Label Grid.Column="0" Content="{DynamicResource myResourceKey}"/>
解决方案
以下 XAML 无效:
MyObservableCollection[DynamicResource myResourceKey]
DynamicResource myResourceKey
必须用常量替换,例如1
或'abc'
。
另一种选择是按照@Martin Zikmund 的建议在视图模型中执行查找,或者使用绑定到和多转换器的多绑定myResourceKey
:MyObservableCollection
https:
//blog.csainty.com/2009/12/wpf-multibinding -and.html
推荐阅读
- amazon-web-services - 如何从 AWS CDK for python 中的 Bucket 对象获取存储桶名称
- javascript - 我有一个对象列表。我想在第一行显示 8 个项目。如果列表长度超过 8 则添加一个显示更多按钮
- ignite - 从 2.7.0 升级到 2.9.0 后,Ignite 客户端不稳定
- javascript - 这是否遵循策略设计模式
- ios - 提交苹果商店以供审核 info.plist 中的 DarkMode UIUserInterfaceStyle 键
- primefaces - 单击数据表时出现黑色边框
- node.js - 本地 Node.js 包中的 CLI 实用程序
- apache-kafka - 实时处理:Storm/flink vs 标准应用(java、c#...)
- amazon-web-services - Secrets Manager - 在另一个账户中使用 lambda 轮换密钥
- azure - Kusto/Azure 数据资源管理器 - 如何使用时间跨度字段对外部表进行分区?