首页 文章

如何在ComboBox中将'Attached property'定义为'SelectedValuePath'?

提问于
浏览
0

嗨,我在ComboBox中绑定有问题 . 我想将ComboBox项绑定到ListView列,并作为选定值返回选定列上定义的附加属性的值 .

在下面的示例中,您可以看到显示所选列宽度的工作示例 . 如果您尝试将ComboBox中的 SelectedValuePath 更改为 (loc:SampleBehavior.SampleValue) ,则会出现绑定错误:

BindingExpression路径错误:'object'''GridViewColumn'上找不到'(u:SearchableListView.SearchMemberPath)'属性

<Window x:Class="Problem_Sample1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:loc="clr-namespace:Problem_Sample1"
  WindowStartupLocation="CenterScreen"
  Title="Window1" 
  Height="300" Width="300">
  <DockPanel>
    <ComboBox DockPanel.Dock="Top"
         x:Name="combobox"
         ItemsSource="{Binding Path=View.Columns, ElementName=listview}"
         DisplayMemberPath="Header"
         SelectedValuePath="Width">
    </ComboBox>

    <StatusBar DockPanel.Dock="Bottom">
      <TextBlock>
        <TextBlock Text="Selected column (value): " />
        <TextBlock Text="{Binding Path=SelectedValue, ElementName=combobox}" />
      </TextBlock>
    </StatusBar>

    <ListView x:Name="listview">
      <ListView.View>
        <GridView>
          <GridViewColumn Header="Name" 
                  Width="101" 
                  loc:SampleBehavior.SampleValue="201" />
          <GridViewColumn Header="Surname" 
                  Width="102" 
                  loc:SampleBehavior.SampleValue="202" />
        </GridView>
      </ListView.View>
    </ListView>
  </DockPanel>
</Window>

SampleBehavior.cs

using System.Windows;
using System.Windows.Controls;

namespace Problem_Sample1
{
  public static class SampleBehavior
  {

    public static readonly DependencyProperty SampleValueProperty =
      DependencyProperty.RegisterAttached(
        "SampleValue",
        typeof (int),
        typeof (SampleBehavior));

    [AttachedPropertyBrowsableForType(typeof(GridViewColumn))]
    public static int GetSampleValue(GridViewColumn column)
    {
      return (int)column.GetValue(SampleValueProperty);
    }

    [AttachedPropertyBrowsableForType(typeof(GridViewColumn))]
    public static void SetSampleValue(GridViewColumn column, int value)
    {
      column.SetValue(SampleValueProperty, value);
    }

  }
}

感谢您的任何帮助或建议 .

1 回答

  • 0

    由于我偶然发现了(这是第一个合理搜索的谷歌搜索结果),我现在也可以写一个答案 .

    请求的功能实际上完全按照询问的方式提供 .

    <ComboBox DockPanel.Dock="Top"
         x:Name="combobox"
         ItemsSource="{Binding Path=View.Columns, ElementName=listview}"
         DisplayMemberPath="Header"
         SelectedValuePath="(loc:SampleBehavior.SampleValue)">
    

    将附加的属性路径放在(大括号)中很重要,否则它会尝试对源对象进行一些奇怪的查找 .

    此外,问题中的错误消息指出“BindingExpression路径错误:在'object'''GridViewColumn' ", so the error message is definitely related to a completely different property and not to "(loc:SampleBehavior.SampleValue)上找不到'(u:SearchableListView.SearchMemberPath)'属性” . 这种不一致似乎是与为减少代码示例而进行的编辑相关的问题

相关问题