【问题标题】:Bind XAML property indirectly间接绑定 XAML 属性
【发布时间】:2013-09-24 05:38:43
【问题描述】:

想象一下,我有一个按钮和一个绑定:

<Button Content="{Binding Path=FailOverStrings.ConfigTestBtn, Source={StaticResource    ResourceWrapper}}></Button>

现在我想设置一个这样的按钮数组:

        <Grid >
            <ItemsControl>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Button Content="{Binding Title}" />
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </Grid>

我将在后面的代码中创建一个集合,但是如何说等于 'ConfigTestBtn' 的 'Title' 并不是真正的字符串 'ConfigTestBtn' 本身,而是 FailOverStrings 的一个属性的名称?

绑定中的某种间接方式。 我想我可以写一个转换器来做,但是真的有必要吗?

【问题讨论】:

  • 不确定我理解你的意思,发布你的ViewModel代码
  • 你说“一个这样的按钮数组”..但是你的网格代码中没有“这样的按钮”..你想达到什么目的?
  • 想象一下,在代码中的某个地方有一个由“ConfigTestBtn”、“ConfigSipBtn”等字符串组成的数组。我想在网格中显示它们。但是字符串本身只是某些资源容器中的属性。因此,在显示按钮网格时,我不想将标题显示为“ConfigTestBtn”。我希望标题显示在第一个示例中 - 作为某个资源对象的属性值

标签: wpf binding indirection


【解决方案1】:

假设你有一个像下面这样的类。

public class FailOverStrings
{
    public FailOverStrings()
    {
        ConfigTestBtn = "Actual value";
    }

    public string ConfigTestBtn { get; set; }
}

那么你的转换器可以是这样的

public class PropertNameToValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string retValue = string.Empty;
        FailOverStrings settings = new FailOverStrings();
        foreach(PropertyInfo pinfo in settings.GetType().GetProperties())
        {
            if (pinfo.Name == value.ToString())
            {
                retValue = pinfo.GetValue(settings, null).ToString();
            }
        }
        return retValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

并在按钮中使用这个转换器

<Window.Resources>
    <local:PropertNameToValueConverter x:Key="PropertNameToValueConverter"></local:PropertNameToValueConverter>
</Window.Resources>
<Grid>
    <Button Content="{Binding ElementName=myWindow, Path=PropertyName, Converter={StaticResource ResourceKey=PropertNameToValueConverter}}" Width="100" Height="30" />
</Grid>

【讨论】:

  • 谢谢,罗纳克。我也想过这个解决方案,但它看起来有点复杂。那么,有没有办法直接在 XAML 中做到这一点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
相关资源
最近更新 更多