【问题标题】:WPF binding TextBox and ObservableDictionary<Int64,String> (display String by Id)WPF 绑定 TextBox 和 ObservableDictionary<Int64,String> (按 Id 显示字符串)
【发布时间】:2012-11-16 18:30:35
【问题描述】:

我的员工列表中的每一项都有Post 属性。此属性为Int64 类型。另外,我有一些 ObservableDictionary&lt;Int64,String&gt; 作为静态属性。每个员工必须通过其键显示String 值。 Employe项的DataTemplate(我删除了多余的):

        <DataTemplate x:Key="tmpEmploye">
            <Border BorderThickness="3" BorderBrush="Gray" CornerRadius="5">
                <StackPanel Orientation="Vertical">                        
                    <TextBlock Text="{Binding Path=Post}"/>
                </StackPanel>
            </Border>                               
        </DataTemplate> 

但此代码显示的是 Int64 值,而不是 String。获取静态字典的字符串:

"{Binding Source={x:Static app:Program.Data}, Path=Posts}"

我知道如何解决ComboBox 的问题,但我不知道TextBlock 的问题。对于ComboBox,我写了它(它工作正常):

<ComboBox x:Name="cboPost" x:FieldModifier="public" Grid.Row="4" Grid.Column="1" HorizontalAlignment="Stretch"
          VerticalAlignment="Stretch" Margin="2" Grid.ColumnSpan="2" 
          ItemsSource="{Binding Source={x:Static app:Program.Data}, Path=Posts}" DisplayMemberPath="Value"
          SelectedValuePath="Key"
          SelectedValue="{Binding Path=Post, Mode=TwoWay}">            
</ComboBox>

但是对于TextBlock,我该如何解决呢?

【问题讨论】:

  • @Blam 通知字典更改。它的签名:ObservableDictionary&lt;TKey,TValue&gt; : NotifyPropertyChangedClass, INotifyCollectionChanged, IDictionary&lt;TKey, TValue&gt; where TKey: IEquatable&lt;TKey&gt;.

标签: wpf xaml binding


【解决方案1】:

嗯嗯,我确信我之前已经为这个场景开发了一些东西,但我不记得或找不到任何相关的东西!

IMO 您可以使用转换器,因此您将 Post (Int64) 传递给转换器,它会从字典中返回字符串值,尽管它必须是更好的解决方案。

[ValueConversion(typeof(Int64), typeof(string))]    
public class PostToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // validation code, etc
        return (from p in YourStaticDictionary where p.Key == Convert.ToInt64(value) select p.Value).FirstOrDefault();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
    }
}

XAML:

<Window ...
    xmlns:l="clr-namespace:YourConverterNamespace"
    ...>
    <Window.Resources>
        <l:PostToStringConverter x:Key="converter" />
    </Window.Resources>
    <Grid>
        <TextBlock Text="{Binding Post, Converter={StaticResource converter}}" />
    </Grid>
</Window>

【讨论】:

  • 是的,我可以。但也许存在更简单的方法,没有 IValueConvereter?这对我来说很有趣。
  • 您可以在 Employee 上创建一个字符串属性并注入正确的值。
  • 我认为更好的方法是实现转换器。这样视图模型就不会受到影响。
猜你喜欢
  • 1970-01-01
  • 2014-12-02
  • 2015-05-24
  • 2010-11-20
  • 2011-10-20
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
相关资源
最近更新 更多