WPF绑定TextBox和ObservableDictionary <int64,string>(按Id显示字符串)</int64,string>

时间:2012-11-16 18:30:36

标签: wpf xaml binding

我的员工列表中的每个项目都有Post属性。此属性为Int64类型。另外,我有一些ObservableDictionary<Int64,String>作为静态属性。每个员工必须按其密钥显示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

1 个答案:

答案 0 :(得分:2)

mmmmm,我确定我之前为这个场景开发了一些东西,但是我记不起来了,或者找不到任何相关内容!

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>