从Code Behind到XAML

时间:2010-08-11 06:03:00

标签: wpf silverlight

我在.cs文件中有以下C#代码,我想把它移到XAML。 代码包含名为:OperationConverte

的属性
Binding binding1 = new Binding("DisplayNames") 
    { 
       Source = OperationConverter, 
    }; 
    ComboBox4.SetBinding(ComboBox.ItemsSourceProperty, binding1); 


    Binding binding2 = new Binding("Operation") 
                      { 
                         Mode = BindingMode.TwoWay, 
                         Converter = (OperationConverter as IValueConverter) 
                      }; 
    ComboBox4.SetBinding(ComboBox.SelectedValueProperty, binding2);     

所以我所做的就是:

   <ComboBox Name="ComboBox4" MinWidth="100"  ItemsSource="{Binding Path=OperationConverter.DisplayNames}" 
                               SelectedValue="{Binding Path=Operation, Mode=TwoWay, 
                               Converter={?????DONT KNOW WHAT TO DO HERE????}}" Margin="30,123,83,148" /> 

但我没有意识到如何连接OperationConverter

1 个答案:

答案 0 :(得分:2)

有多种方法可以做到,但标准做法是将转换器的实例声明为资源并引用它。

<Window.Resources>
    <local:OperationConverter x:Key="MyConverter" />
</Window.Resources>

和更新的绑定

SelectedValue="{Binding Path=Operation, Mode=TwoWay, Converter={StaticResource MyConverter}}"

当前暴露转换器的方式最好不要实现IValueConverter,而是从OperationConverter对象中公开转换后的值并直接绑定到该属性。