【问题标题】:Picker SelectedItem Binding Issue in Xamarin FormsXamarin 表单中的选取器 SelectedItem 绑定问题
【发布时间】:2018-11-15 02:13:55
【问题描述】:

我有一个绑定到 ObservableCollection 对象的 Picker。这些项目是从 Web 服务(json 数据)填充的。

选择器正确显示数据,但 SelectedItem 不起作用。

这是我的 xaml 代码:

  <Picker
        ItemsSource="{Binding RatesTax}"
        ItemDisplayBinding="{Binding Code}"
        SelectedItem="{Binding SourceRate, Mode=TwoWay}">

    </Picker>

RatesTax 是 RatesView 类的对象

 public class RatesView 
{
    public string Code
    {
        get; set;
    }

    public double TaxRate
    {
        get; set;
    }      
}

这就是属性

 public ObservableCollection<RatesView> RatesTax { get; set; }

这是 sourceRate 属性

private RatesView sourceRate;

和 SourceRate 属性

   public RatesView SourceRate
    {
        set
        {
            if (sourceRate != value)
            {
                sourceRate = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SourceRate"));
            }
        }
        get
        {
            return sourceRate;
        }
    }

我在 SourceRate 中放置了一个断点,以查看当我选择选择器的一些数据时它是否进入,但它没有进入 SourceRate 过程。我认为 SelectedItem="{Binding SourceRate} 没有按预期工作。

感谢您的宝贵时间!

【问题讨论】:

  • SelectedItem 和 ItemsSource 的类型不匹配
  • 感谢您的回答!所以 SourceRate new 成为 RatesTax 对象?

标签: c# data-binding xamarin.forms binding picker


【解决方案1】:

SelectedItem 属性必须与集合中的项目类型相同。因此,在您的情况下,SourceRate 属性及其支持字段 sourceRate 必须是 RatesView 类型。

另外,通过在绑定中设置 Mode=TwoWay 来确保您的绑定是双向的:

<Picker
    ItemsSource="{Binding RatesTax}"
    ItemDisplayBinding="{Binding Code}"
    SelectedItem="{Binding SourceRate, Mode=TwoWay}">
</Picker>

【讨论】:

  • public RatesView SourceRate { set { if (sourceRate != value) { sourceRate = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SourceRate")); } } get { return sourceRate; } } private RatesView sourceRate;
  • 是的,但不要忘记也让你的支持字段sourceRate 输入RatesView
  • 我进行了更改但仍然无法正常工作,如果我在public RatesView SourceRate { 中设置了一个断点,那么当您从选择器中选择一项时它必须停止?因为它没有弯腰。
  • 尝试将绑定更改为如下所示:SelectedItem="{Binding SourceRate, Mode=TwoWay}"
  • 你是说如果你在SourceRate设置器中设置了一个断点,当你改变选择的项目时它不会被命中?
【解决方案2】:

这可能是 Xamarin 方面的错误。如果您将 SourceRate 设为字符串,您将在选择时获得您选择的代码。由于某种原因,它不会路由绑定的对象,而只会显示值。这似乎不是一种期望/预期的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-05
    • 2018-01-03
    • 1970-01-01
    • 2018-10-20
    • 2021-11-08
    • 1970-01-01
    • 2018-02-01
    • 2016-03-09
    相关资源
    最近更新 更多