UpdateSourceTrigger按钮单击转换器

时间:2013-01-23 11:44:48

标签: c# wpf converter

使用以下代码,在更新/更改其中一个DependencyProperties时,将调用Convert方法。

我希望仅在单击按钮时调用转换器。 我怎么能这样做?

以下是代码:

 <Button Content="Create Project">

                <Button.CommandParameter>
                    <MultiBinding Converter="{StaticResource MyConverter}" UpdateSourceTrigger="Explicit"  Mode="TwoWay">
                        <Binding Path="Text" ElementName="txtDesc"/>
                        <Binding Path="Text" ElementName="txtName"/>
                        <Binding Path="SelectedItem" ElementName="ListBox"/>
                        <Binding Path="SelectedItem.Language" ElementName="TreeView"/>
                    </MultiBinding>
                </Button.CommandParameter>

            </Button>

2 个答案:

答案 0 :(得分:1)

我认为会纠正这样的代码:

<强> XAML

 <Button Content="Create Project" Click="Button_Click"/>

<强> CS

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        string param1 = txtDesc.Text;
        string param2 = txtName.Text;
        object param3 = ListBox.SelectedItem;
        object param4 = TreeView.SelectedItem;

        object convertResult = MyConverterUtils.Convert(param1, param2, param3, param4);
        (sender as Button).CommandParameter = convertResult;
        //or you can execute some method here instead of set CommandParameter
    }


    public class MyConverterUtils 
    {
         //convert method
         //replace Object on your specific types 
         public static Object Convert(string param1, string param2,Object  param3,Object param4)
         {
             Object convertResult=null;

             //convert logic for params and set convertResult
             //for example convertResult = (param1 + param2).Trim();

             return convertResult;
         } 
    }

答案 1 :(得分:-1)

使用MVVM可以非常轻松:

  1. 使用RelayCommand在您的MVVM中声明ICommand
  2. 将Button的Command属性绑定到声明的命令。
  3. 在Command的Execute方法中执行您的逻辑。
  4. 更新所需的属性。
  5. <强>视图模型

        public class MyViewModel : INotifyPropertyChanged
        {
            public ICommand UpdateSomething { get; private set; }
    
            public MyViewModel()
            {
                UpdateSomething = new RelayCommand(MyCommandExecute, true);
            }
    
            private void MyCommandExecute(object parameter)
            {
                // Your logic here, for example using your converter if
                // you really need it.
    
                // At the end, update the properties you need
                // For example adding a item to an ObservableCollection.
            }
        }
    

    <强> XAML

        <Button Content="Create Project" Command="{Binding UpdateSomething}"/>