【问题标题】:Combobox ItemsSource through objectdataprovider by passing in a method parameterCombobox ItemsSource 通过 objectdataprovider 通过传入一个方法参数
【发布时间】:2012-09-26 23:44:24
【问题描述】:

我想从对象数据提供者填充组合框控件项。对象数据提供者调用我的自定义类的方法来获取项目列表。

但是,我的自定义类上的方法需要一个参数才能返回项目列表。我不知道该怎么做。

这是我的尝试:

对象数据提供者声明:

<ObjectDataProvider x:Key="dataFromEnum" ObjectType="{x:Type ns:MyDataProvider}" MethodName="GetData">
            <ObjectDataProvider.MethodParameters>
                <sys:String>String.Empty</sys:String>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

组合框声明:

<ComboBox Name="combobox" ItemsSource="{StaticResource dataFromEnum}" Tag="{Binding Path=Name}" />

如您所见,组合框的 Tag 属性绑定到父级数据上下文的 Name 属性。我想将该 Name 属性传递给对象数据提供者。我不确定如何在向对象数据提供者请求数据时将数据传递给它。

请指教。

谢谢。

【问题讨论】:

    标签: wpf binding objectdataprovider method-parameters


    【解决方案1】:

    有绑定到方法参数以调整其值的示例,但这并不适用于这里...

    面对这一挑战,为什么不让 ViewModel 公开一个属性以绑定到组合控件的 ItemsSource?

    我通常会有类似的东西:

    public MySomething SelectedSomething { get; set; }
    public IEnumerable<MySomething> AvailableSomethings
    {
      get { /* Access a factory method or something to return applicable list for this view model state */ }
    }
    

    那么绑定就变成了:

    <ComboBox ItemsSource="{Binding path=AvailableSomethings}" SelectedItem="{Binding path=SelectedSomething}"/>
    

    【讨论】:

    • 好吧,我觉得我做不到。此组合框正在网格控件内呈现。网格控件本身绑定到一个 IEnumerable。所以会有多行,每一行都有一个组合框。每个组合框可能必须根据类型在内部呈现一组不同的选项。这就是复杂性。正如您所描述的,我无法在我的视图模型中定义属性,因为组合框是在网格中的每行生成的。而且我不知道有多少行(所以有多少组合框)。
    【解决方案2】:

    在 wpf 中,您必须为选择更改生成事件 为此,您必须提供参考

    clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity
    
     <ComboBox ItemsSource="{Binding UserSectionItems, Mode=TwoWay}" Margin="104,11,0,10" HorizontalAlignment="Left" Width="135" Name="UserCmd" >
                <l:Interaction.Triggers>
                    <l:EventTrigger EventName="SelectionChanged">
                        <l:InvokeCommandAction Command="{Binding UserComboBoxSelectionCmd, Mode=TwoWay}" CommandParameter="{Binding ElementName=UserCmd,Path=SelectedItem}"/>
                    </l:EventTrigger>
                </l:Interaction.Triggers>
            </ComboBox>
    

    在你的 Viewmodel 中看起来像

    public RelayCommand<string> UserComboBoxSelectionCmd { get; set; }
    

    【讨论】:

    • 请看我上面的评论。我的评论也适用于您的解决方案。我不能按照你描述的方式做。
    猜你喜欢
    • 2010-12-09
    • 2015-01-15
    • 2016-02-24
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多