WPF CommandParameter MultiBinding值为null

时间:2012-12-04 23:27:57

标签: c# wpf binding .net-4.0 multibinding

我只是尝试将两个控件绑定为命令参数,并将它们作为object[]传递给我的命令。

XAML:

<UserControl.Resources>
        <C:MultiValueConverter x:Key="MultiParamConverter"></C:MultiValueConverter>
    </UserControl.Resources>

    <StackPanel Orientation="Vertical">
        <StackPanel Orientation="Horizontal">
            <Button Name="Expander" Content="+" Width="25" Margin="4,0,4,0" Command="{Binding ExpanderCommand}">
                <Button.CommandParameter>
                    <MultiBinding Converter="{StaticResource MultiParamConverter}">
                        <Binding ElementName="Content"/>
                        <Binding ElementName="Expander"/>
                    </MultiBinding>
                </Button.CommandParameter>
            </Button>
            <Label FontWeight="Bold">GENERAL INFORMATION</Label>
        </StackPanel>
        <StackPanel Name="Content" Orientation="Vertical" Visibility="Collapsed">
            <Label>Test</Label>
        </StackPanel>
    </StackPanel>

命令:

public ICommand ExpanderCommand
        {
            get
            {
                return new RelayCommand(delegate(object param)
                    {
                        var args = (object[])param;
                        var content = (UIElement)args[0];
                        var button = (Button)args[1];
                        content.Visibility = (content.Visibility == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible;
                        button.Content = (content.Visibility == Visibility.Visible) ? "-" : "+";
                    });
            }
        }

转换器:

public class MultiValueConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return values;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException("No two way conversion, one way binding only.");
        }
    }

基本上发生的事情是绑定似乎工作正常并且转换器返回包含正确值的object[],但是当命令执行时,param是包含相同数字的object[]元素除外null

有人可以告诉我为什么object[]参数的值设置为null吗?

谢谢, 亚历克斯。

1 个答案:

答案 0 :(得分:15)

这样做:

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    return values.ToArray();
}

请查看此question以获取解释。