【问题标题】:Binding Textblock to a Dictionary value where key is given by the user input将文本块绑定到字典值,其中键由用户输入给出
【发布时间】:2020-01-31 17:14:02
【问题描述】:

以上是我想要获得的期望行为。 Instrument 中的值应用作访问存储价格的字典的键。 假设我们有一些货币集合,它们在项目控件中显示,如下所示:

<ItemsControl Background="White" Name="currenciesList" ItemsSource="{Binding Currencies}">

我们定义了一个数据模板来描述如何使用以下属性来呈现列表中的每种货币:

<ComboBox Name="cmbbx" Height="20" Width="60" Grid.Column="1" ItemsSource="{Binding Path=InstrumentTypes}" SelectedItem="{Binding CurrencyInstrument}"  IsSynchronizedWithCurrentItem="False">
</ComboBox>
<TextBlock Name="purchase_price" Grid.Column="2" Text="{Binding What do I put here??}">
</TextBlock>
<TextBlock Name="sale_price" Grid.Column="3" Text="{Binding What do I put here??}"/>

对于文本块绑定,我想要一个像 PurchaseInstruments[CurrencyInstrument] 这样的表达式,其中 PurchaseInstruments 是 Dictionary 属性,CurrencyInstrument 是另一个存储要在字典中使用的键值的属性。我怎样才能实现这种行为?

请忽略图片中的不良格式。

【问题讨论】:

    标签: c# wpf dictionary data-binding


    【解决方案1】:

    通过将文本框直接绑定到组合框中的选定值来解决问题。关键的见解是将购买和销售价格封装在 CurrencyInstrument 对象中,以便我们可以在绑定到文本框时直接访问属性。下面是 XAML 代码。

    <ComboBox Name="cmbbx" Height="20" Width="60" Grid.Column="1" SelectedIndex="0" ItemsSource="{Binding Path=InstrumentTypes}" DisplayMemberPath="Key" SelectedValuePath="Value" IsSynchronizedWithCurrentItem="False"></ComboBox>
    <TextBlock Name="purchase_price" Grid.Column="2" Text="{Binding ElementName=cmbbx, Path=SelectedValue.PurchasePrice}"/>
    <TextBlock Grid.Column="3" Text="{Binding ElementName=cmbbx, Path=SelectedValue.SalePrice}"/>
    
    
    

    【讨论】:

      【解决方案2】:

      字典本质上是一个 KeyValuePair 类型,因此您的 XAML 应该如下所示:

      <ComboBox Name="cmbbx" Height="20" Width="60" Grid.Column="1" 
            ItemsSource="{Binding Path=InstrumentTypes}" 
            SelectedValue="{Binding CurrencyInstrument}"  
            IsSynchronizedWithCurrentItem="False" DisplayMemberPath="Key" SelectedValuePath="Value"/>
      
      <TextBlock Name="purchase_price" 
             Grid.Column="2" 
             Text="{Binding CurrencyInstrument.PurchasePrice}"/>
      
      <TextBlock Name="sale_price" 
             Grid.Column="3" 
             Text="{CurrencyInstrument.SalePrice}"/>
      

      【讨论】:

      • 感谢您的回复,它启发我重构我的设计,将 CurrencyInstrument 表示为具有购买价格和销售价格的对象,而不是字典中的键值对。现在我的问题是我目前将 SelectedValue 绑定到我的 ViewModel 中的一个变量,但这会导致所有货币的工具类型发生变化。但是,我希望每种货币都能够独立更改。我是否需要维护与每种货币对应的此类变量的列表?
      猜你喜欢
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2018-11-30
      • 2014-07-19
      相关资源
      最近更新 更多