簡體   English   中英

使用MVVM模式在WPF中從視圖模型到視圖進行條件綁定

[英]Conditional binding from view model to view in WPF using MVVM pattern

我正在使用MVVM模式開發WPF應用程序。 我在視圖中有一個組合,而在視圖模型中有兩個列表(項目和組織)。 根據組織列表項的不同,我必須綁定組織名稱。 例如,如果組織列表的Count屬性為1,則組合框項目必須為“ ProjectName” ;如果組織列表的Count屬性大於1,則組合框項目應類似於“ ProjectName-OrganizationName” 這是我擁有的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>

您可以選擇幾種方法來實現此目的,但我認為最好的是:

在您的數據上下文中添加一個屬性,該屬性將稱為“ FullName”或其他名稱。 這將返回:(偽)如果Projects count> 0,則返回Name +'-'+ ProjectName,否則返回Name

然后將DisplayMemberPath綁定到FullName。

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM