2010-10-29 80 views
0

我想弄清楚它是否可能通过后面的代码更新IValueConverter。通过代码更新IValueConverter代码

我的情况是我有两个组合框。一旦更新第一个,我将第二个的ItemsSource属性更改为各种枚举之一。我从CodeProject中抓取了一个EnumToFriendlyNameConverter,但我不知道如何设置它。

如果我在ItemsSource中设置了转换器(见下文),那么当我下一次设置项目源时它会被忽略。

ItemsSource="{Binding Converter={StaticResource enumItemsConverter}}"

我发现,可以通过使用一个ItemTemplate但后来我不得不手动放置在一个标签,然后有不同的风格,我的其他组合框。正确获取样式似乎有很多工作...

回答

2

当您更改ItemsSource时,您只需再次应用转换器或修改ItemsSource而不是替换它。

例如创建一个新的绑定:

private void ChangeItemsSouce(IEnumerable newItems) 
{ 
    Binding binding = new Binding(); 
    binding.Source = newItems; 
    binding.Converter = new EnumToFriendlyNameConverter(); 
    comboBox.SetBinding(ComboBox.ItemsSourceProperty, binding); 
} 

或修改现有绑定:

private void ChangeItemsSouce(IEnumerable newItems) 
{ 
    var binding = comboBox.GetBindingExpression(ComboBox.ItemsSourceProperty); 
    binding.ParentBinding.Source = newItems; 
} 
+0

我不认为我的代码到了测试,但它听起来很有道理,所以我会假设你'对了。谢谢 :) – Ian 2011-05-05 08:06:53