【问题标题】:Conditional binding from view model to view in WPF using MVVM pattern使用 MVVM 模式从视图模型到 WPF 中的视图的条件绑定
【发布时间】:2015-05-11 07:07:27
【问题描述】:

我正在使用 MVVM 模式开发 WPF 应用程序。我在视图中有一个组合,在视图模型(项目和组织)中有两个列表。根据组织列表项,我必须绑定组织名称。 例如,如果组织列表的 Count 属性为 1,则组合框项必须为 "ProjectName",如果组织列表的 Count 属性大于 1,则组合框项应类似于 >“项目名称 - 组织名称”。 这是我拥有的 XAML 代码:

<ComboBox x:Name="textBox3" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Projects}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding Path=SelectedProject}">
        </ComboBox>

我应该如何实现这个目的。我希望能有一点帮助。干杯。

我在视图模型中添加了属性 projectFullName 但我得到了一个空的组合框:

 public string ProjectFullName
    {
        get
        {
            if (this.organizations.ToList().Count > 1)
            {
                this.projectFullName = string.Format("{}{0} - {1}", this.selectedProject.Name, this.organizations.First(org => org.Id == this.selectedProject.OrganizationId).Name);
            }
            else if (this.organizations.ToList().Count == 1)
            {
                this.projectFullName = this.selectedProject.Name;
            }
            return this.projectFullName;
        }
    }

XAML 代码:

<ComboBox x:Name="textBox3" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=Projects}" DisplayMemberPath="{Binding Path=ProjectFullName}" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding Path=SelectedProject}">

        </ComboBox>

【问题讨论】:

  • 你需要使用datatemplate和datatriggers
  • 但是怎么用呢,能给我举个例子吗
  • google 是你的朋友,那里有很多例子

标签: c# wpf xaml mvvm combobox


【解决方案1】:

您有多种选择来实现这一点,但我认为最好的是:

向您的数据上下文添加一个属性,该属性将被称为“FullName”之类的。 那将返回:(伪) 如果项目数 > 0 则 返回名称 + '-' + 项目名称 否则返回名称

然后将 DisplayMemberPath 绑定到 FullName。

【讨论】:

  • 如何绑定到 displaymemebrPath,因为现在我绑定了在视图模型中创建的属性后,组合框项不显示了。
  • 视图模型中未创建“FullName”属性。 ItemsSource DataContext 设置为模型列表,所以 DataContext 是模型,因此需要在模型中创建 FullName,然后将 DisplayMemberPath 绑定到它。
【解决方案2】:

Datatrigger 确实是您的朋友。确保 ComboBox 没有设置 DisplayMemberPath,因为这会覆盖样式设置器。

<Style x:Key="MyStyle"  TargetType="ComboBox">
        <Setter Property="DisplayMemberPath" Value="DefaultName"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Items.Count}" Value="1">
                <Setter Property="DisplayMemberPath" Value="OtherName"/>
            </DataTrigger>
        </Style.Triggers>
 </Style>

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2018-10-25
    • 2023-03-06
    相关资源
    最近更新 更多