【问题标题】:wpf converter binding - dynamic binding in wrong orderwpf转换器绑定-错误顺序的动态绑定
【发布时间】:2010-08-05 08:42:42
【问题描述】:

我正在尝试使用转换器将组合框与 Tabitems 绑定

我的转换器类如下

public class TabItemsCollection : IValueConverter  
{
   >public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
   {  
      ItemCollection collection = value as ItemCollection;  
      IList<string> names = new List<string>();  
      foreach (TabItem ti in collection.SourceCollection)  
      {  
           names.Add(ti.Header.ToString());  
      }  
      return names;  
    }   

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

我的xaml如下

//组合框


<ComboBox Name="cmbModule" 
ItemsSource="{Binding ElementName=mnuMain, Path=Items, Converter={StaticResource MenuItemsConverter}}" SelectedIndex="{Binding ElementName=mnuMain, Path=SelectedIndex}">
   <ComboBox.ItemTemplate>
       <DataTemplate>
           <TextBlock Text="{Binding}"/>
       </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>  

//选项卡控件


<local:MenuTab Name="mnuMain"></local:MenuTab>  

我正在将“mnuMain”与作为代码隐藏中的自定义选项卡控件的项目绑定,因为我这样做时无法使用 tabitems 来推广组合框,因为转换器首先触发,然后是“mnuMain”。如果我在 xaml 中创建 Tabitems,组合框中会填充 tabitems,但我的问题是动态绑定。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    有一种方法可以强制您的绑定再次更新:

    cmbModule.GetBindingExpression(ComboBox.ItemsSourceProperty).UpdateTarget();
    

    另一种选择是创建一个包含选项卡集合的 DependecyProperty,然后将 Combobox 和 MenuTab 绑定到相同的属性。 SelectedIndex 可以像现在一样完成。

    第三种选择是创建一个 ObservableCollection 类型的属性来保存所需的信息,然后创建 2 个转换器,一个用于转换为 tabitem,1 个用于转换为 Combobox 项。如果您在集合中添加或删除项目,绑定将自动触发。

    【讨论】:

    • 感谢您的解决方案。在处理TextBox 时,我使用txtFrequencyEditMode.GetBindingExpression(TextBox.TextProperty).UpdateSource() 来更新源代码!
    猜你喜欢
    • 2010-11-11
    • 1970-01-01
    • 2010-12-30
    • 2016-12-18
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    相关资源
    最近更新 更多