首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF绑定TextBox和ObservableDictionary<Int64,String> (按Id显示字符串)

WPF绑定TextBox和ObservableDictionary<Int64,String> (按Id显示字符串)
EN

Stack Overflow用户
提问于 2012-11-17 02:30:36
回答 1查看 735关注 0票数 1

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

代码语言:javascript
复制
        <DataTemplate x:Key="tmpEmploye">
            <Border BorderThickness="3" BorderBrush="Gray" CornerRadius="5">
                <StackPanel Orientation="Vertical">                        
                    <TextBlock Text="{Binding Path=Post}"/>
                </StackPanel>
            </Border>                               
        </DataTemplate> 

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

代码语言:javascript
复制
"{Binding Source={x:Static app:Program.Data}, Path=Posts}"

我知道如何为ComboBox解决问题,但我不知道如何为TextBlock解决这个问题。对于ComboBox,我写了它(它工作得很好):

代码语言:javascript
复制
<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解决这个问题呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-17 02:46:13

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

您可以使用转换器,因此您将Post (Int64)传递给转换器,它将返回字典中的字符串值,尽管这肯定是一个更好的解决方案。

代码语言:javascript
复制
[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:

代码语言:javascript
复制
<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>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13422349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档