【问题标题】:How to bind directly properties in xaml uwp如何在xaml uwp中直接绑定属性
【发布时间】:2017-10-06 15:03:15
【问题描述】:
 public sealed partial class MainPage : Page
    {
        //public static dynamic resource;

        public  ResourceModel vm = new ResourceModel();        

        public MainPage()
        {
            this.InitializeComponent();              
        }
     }


public class ResourceModel 
    {
        private Dictionary<string, string> _resource;
        public Dictionary<string, string> Resource
        {
            get { return _resource; }
            set
            {
               _resource=Value;
            }
        }
    }

Xaml 代码

<TextBlock Text="{Binding vm.Resource[Account] ,Mode=TwoWay}" FontSize="15" Margin="10 0 30 0" Foreground="White" VerticalAlignment="Top" HorizontalAlignment="Center" Grid.Row="1" Grid.Column="0"></TextBlock>

说明 我想从没有 DataContext 和文本块名称的 ResourceModel 绑定我的文本块。只有我需要使用属性名称进行绑定。

【问题讨论】:

  • 使用 x:Bind? Text="{x:Bind vm.Resource[Account] ,Mode=TwoWay}" .
  • @mm8 Error Invalid binding path 'vm.Resource[Account]' 无效索引
  • @mm8 如何传递字符串“Account”

标签: c# xaml uwp


【解决方案1】:

您错过了一些地方。以下是关于 em 的一些信息:

  1. Binding 正在搜索不可用的数据上下文。如果您没有viewmodel 并且您想使用旧版binding 将UI 元素绑定到您需要在xaml&lt;Page&gt; 标记中添加DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"。这将告诉绑定引擎您正在绑定到后面的代码。
  2. 另外,您不能绑定到字段,您只能绑定到properties,因为字段没有getset。因此,在您的 vm 后面的代码中是一个字段而不是一个属性。将其更改为public ResourceModel vm { get; set; } = new ResourceModel();,它将开始工作。

话虽如此,您可以通过 3 种方法来解决问题:

1。使用binding 进行代码隐藏:

&lt;page&gt; 标记中添加DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}" 用于告诉绑定引擎您将绑定到后面的代码。

您的textblock 代码如下所示:

<TextBlock Text="{Binding vm.Resource[Account]}"/>

我不明白为什么将Mode 设置为two way,因为它是Textblock 并且不可编辑,而旧版binding 默认为oneWay

2。使用bindingResourceModel

另一种方法是将textblock 的数据上下文设置为直接绑定到模型。下面是代码:

 <TextBlock Text="{Binding Resource[Account]}">
       <TextBlock.DataContext>
            <local:ResourceModel/>
       </TextBlock.DataContext>
  </TextBlock>

3。使用x:bind 绑定代码

x:bind 默认绑定到后面的代码,因此您可以使用x:bind 而不是绑定。 x:bind 面临的问题是因为在使用 x:bind 时无法在 xaml 中设置密钥。使用转换器,然后将您的密钥作为转换器参数传递,它就会开始正常工作。如果您确实打算使用它,下面是 xaml 代码:

<TextBlock Text="{x:Bind vm.Resource,Converter={StaticResource DictionaryValueFetcher},ConverterParameter='account'}"/>

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 2013-09-24
    • 2020-01-29
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    相关资源
    最近更新 更多