【问题标题】:Binding a value to an extension of a view in Xamarin在 Xamarin 中将值绑定到视图的扩展
【发布时间】:2019-11-26 14:33:16
【问题描述】:

我正在尝试将列表中的整数值链接到 StackLayout 的扩展值“索引”。无论我尝试做什么,尽管将所有数据都设置为“7”(随机),但该值始终为 0。

扩展代码如下:

 public class NamedStackLayout : StackLayout
    {
        public string Name { get; set; }
        public int Index { get; set; }

        public static readonly BindableProperty IndexProperty = BindableProperty.Create("Index", typeof(int), typeof(NamedStackLayout), 1);

        public int IndexValue
        {
            get { return (int)GetValue(IndexProperty); }
            set { SetValue(IndexProperty, value); }
        }
    }

【问题讨论】:

  • 可以吗?

标签: c# android ios xamarin


【解决方案1】:

你需要实现 INotifyPropertyChanged

并覆盖此方法

protected void OnPropertyChanged(string propertyName)
{
    var handler = PropertyChanged;
    if (handler != null)
        handler(this, new PropertyChangedEventArgs(propertyName));
}

之后在 IndexValue 的设置器中调用 OnPropertyChanged

【讨论】:

    【解决方案2】:

    在您的情况下,您应该使用 IndexValue 属性获得正确的值。

    例如:

    您在 xaml 中绑定索引:

      <local:NamedStackLayout x:Name="nameStackLayout" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Index="7">
         VerticalOptions="FillAndExpand"></local:MyWeb>
      </local:NamedStackLayout>
    

    那么你可以得到价值:

      var index = nameStackLayout.IndexValue;//here you could get the correct value 7.
    

    或者您可以在自定义堆栈布局中定义 Index 属性,保持名称与 BindableProperty 名称相同:

    class NamedStackLayout:StackLayout
    {
        public string Name { get; set; }
    
        public static readonly BindableProperty IndexProperty = BindableProperty.Create("Index", typeof(int), typeof(NamedStackLayout), 1);
    
        public int Index
        {
            get { return (int)GetValue(IndexProperty); }
            set { SetValue(IndexProperty, value); }
        }
    }
    

    那么您可以使用Index 属性获得正确的值。

    例如:

    var index = nameStackLayout.Index;//here you could get the correct value 7.
    

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多