WPF ComboBox 在一个 DataTrigger 后不能显示 SelectedItem,但在另一个 DataTrigger 中可以

5
所以,我有一个组合框,我想要重复使用它来处理多个数据集,而不是拥有3个单独的组合框。也许这很糟糕,有人可以告诉我。我接受所有的想法和建议。我只是想清理一些代码,认为一个组合框比3个更干净。无论如何,当另一个ComboBox的值更改时,ItemsSource和SelectedItem都应该更改,这会引发未工作的ComboBox的PropertyChanged值。最糟糕的部分是当CurSetpoint.ActLowerModeIsTimerCondition为真时,它总是正确加载SelectedItem,但从那里到CurSetpoint.ActLowerGseMode为True时,组合框没有加载SelectedItem。
这是具有问题的ComboBox的XAML。
<ComboBox Grid.Row="1" Grid.Column="1" Margin="5,2" VerticalAlignment="Center" Name="cmbActTimersSetpointsGseVars">
       <ComboBox.Style>
          <Style BasedOn="{StaticResource {x:Type ComboBox}}" TargetType="{x:Type ComboBox}">
             <Style.Triggers>
                <DataTrigger Binding="{Binding Path=CurSetpoint.ActLowerModeIsTimerCondition}" Value="True">
                   <Setter Property="ItemsSource" Value="{Binding TimerInstances}" />
                   <Setter Property="SelectedItem" Value="{Binding CurSetpoint.ActLowerTimerInstance, Mode=TwoWay}" />
                   <Setter Property="DisplayMemberPath" Value="DisplayName"></Setter>
                   <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=CurSetpoint.ActLowerGseMode}" Value="True">
                   <Setter Property="ItemsSource" Value="{Binding EnabledGseVars}" />
                   <Setter Property="SelectedItem" Value="{Binding CurSetpoint.ActLowerGseVar, Mode=TwoWay}" />
                   <Setter Property="DisplayMemberPath" Value="DisplayName"></Setter>
                   <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=CurSetpoint.ActModeIsLogicCondition}" Value="True">
                   <Setter Property="ItemsSource" Value="{Binding SetpointStates}" />
                   <Setter Property="SelectedItem" Value="{Binding CurSetpoint.ActSetpoint1State, Mode=TwoWay}" />
                   <Setter Property="DisplayMemberPath" Value="Value"></Setter>
                   <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=CurSetpoint.ShowActLowerCmbBox}" Value="False">
                   <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
             </Style.Triggers>
          </Style>
       </ComboBox.Style>
</ComboBox>

这是两个组合框的图片。当模式从Timer更改为Variable时,尽管其绑定不为空且其实例和itemssource实例数据没有更改,但它不会加载任何内容。但是如果我从Variable切换到Timer,则Timer:1会正确显示。

enter image description here

这里是模型代码,用于改变模式下拉框的值。还包括另外两个属性,即所涉及的下拉框的SelectedItems。以及ItemsSource的属性。
private VarItem actLowerMode;
public VarItem ActLowerMode
{
   get { return this.actLowerMode; }
   set
   {
      if (value != null)
      {
         var oldValue = this.actLowerMode;

         this.actLowerMode = value;
         config.ActLowerMode.Value = value.ID;

         //if they weren't the same we need to reset the variable name
         //Note: 5/21/19 Needs to be this way instead of before because when changing from Timer->GseVariable it wouldn't change the config value because it
         //thought it was still a timer condition because the value hadn't been changed yet.
         if (oldValue != null && (oldValue.CheckAttribute("timer") != value.CheckAttribute("timer")))
         {
            if (value.CheckAttribute("timer"))
            {
               ActLowerTimerInstance = model.TimerInstances.First();
            }
            else
            {
               ActLowerVarName = "";
               if (GseMode)
               {
                  ActLowerGseVar = model.EnabledGseVars.FirstOrDefault();
               }
            }
         }

         RaisePropertyChanged("ActLowerMode");
         RaisePropertyChanged("HasActLowerScale");
         RaisePropertyChanged("ActLowerGseMode");
         RaisePropertyChanged("HasActLowerVarName");
         RaisePropertyChanged("ActLowerModeIsConstant");
         RaisePropertyChanged("ActLowerRow1Label");
         RaisePropertyChanged("ActLowerModeIsTimerCondition");
         RaisePropertyChanged("ShowActLowerConstTextBox");
         RaisePropertyChanged("ShowActLowerCmbBox");
         RaisePropertyChanged("ShowActLowerRow1Label");
         if (GseMode)
         {
            RaisePropertyChanged("ActLowerGseMode");
         }
      }
   }
}

private GseVariableModel actLowerGseVar;
public GseVariableModel ActLowerGseVar
{
   get { return this.actLowerGseVar; }
   set
   {
      if (value != null)
      {
         this.actLowerGseVar = value;
         if (!ActLowerModeIsTimerCondition)//only changing the config value if its not set to timer
         {
            config.ActLowerVarName.Value = value.Number.ToString();
         }
         RaisePropertyChanged("ActLowerGseVar");
      }
   }
}      

private INumberedSelection actLowerTimerInstance;
public INumberedSelection ActLowerTimerInstance
{
   get { return this.actLowerTimerInstance; }
   set
   {
      if (value != null)
      {
         this.actLowerTimerInstance = value;
         config.ActLowerVarName.Value = value.Number.ToString();
         RaisePropertyChanged("ActLowerTimerInstance");
      }
   }
}

public ObservableCollection<INumberedSelection> TimerInstances { get { return this.timerInstances; } }

public ObservableCollection<GseVariableModel> EnabledGseVars
{
   get 
   {
      return enabledGseVariables; 
   }
}

我确定我可能忽略了一些重要信息,所以如果你们有任何问题或需要详细信息,我会进行更新。
更新:正如悬赏所述。如果我在这里做的不是一个好主意,并且有更好的方法,请有经验的人告诉我为什么以及我应该如何。如果有更好的方法而我正在做的是错误的,我只需要知道。

欢迎随时加入WPF聊天室进行讨论... - Lynn Crumbling
是否有可能将“CurSetpoint”从3个布尔值改为枚举类型?因为我好奇只检查true的3个DataTriggers是否会有问题。例如,当“ActModeIsLogicCondition”和“ActLowerModeIsTimerCondition”都为真时会发生什么?或者这不可能发生吗? - Ginger Ninja
@GingerNinja 不应该是可能的,但我会再次检查逻辑并回复您。通过将其切换为枚举,您是说像拥有类似CurSetpoint.ActLowerEnumValue这样的东西,并寻找1、2、3或4种类型的情况吗? - Birdbuster
@Birdbuster 是的。因此,您的DataTrigger将像switch语句一样工作,而不是连续的if语句。通常,如果我在触发器集中有超过2个选项,我会尝试使用枚举。 - Ginger Ninja
1个回答

5

绑定多个ComboBox并设置它们的Visibility没有问题。首先,与您帖子中的代码相比,它大大降低了复杂性。

尽管如此,您可以通过在视图模型和视图之间引入其他抽象来轻松交换ItemsControlcontext(不要与DataContext混淆)。

具体方法如下:

  1. 创建一个包含相关属性的context对象
  2. context应用到您的ItemsControl
  3. context更改时重新绑定属性

您提出按实体收集属性的想法确实不错,但是实现可以更好,无论是视图模型还是视图都看起来很臃肿。这就是这个context对象的作用,当您反复切换上下文时,收集和保持状态。

从我们的模型类开始。让我们针对接口编写代码(即使ItemsSource是未类型化的)。

namespace WpfApp.Models
{
    public interface IEntity
    {
        string Name { get; }
    }

    public class Dog : IEntity
    {
        public Dog(string breed, string name)
        {
            Breed = breed;
            Name = name;
        }

        public string Breed { get; }
        public string Name { get; }
    }

    public class Author : IEntity
    {
        public Author(string genre, string name)
        {
            Genre = genre;
            Name = name;
        }

        public string Genre { get; }
        public string Name { get; }
    }
}

接下来,我们从上下文开始介绍ViewModels。
namespace WpfApp.ViewModels
{
    public class ItemsContext : ViewModelBase
    {
        public ItemsContext(IEnumerable<IEntity> items)
        {
            if (items == null || !items.Any()) throw new ArgumentException(nameof(Items));

            Items = new ObservableCollection<IEntity>(items);
            SelectedItem = Items.First();
        }

        public ObservableCollection<IEntity> Items { get; }

        private IEntity selectedItem;
        public IEntity SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                OnPropertyChanged();
            }
        }

        public string DisplayMemberPath { get; set; }
    }
}

正如所说,相关属性,带有SelectedItem的通知,没有什么特别之处。我们立即看到了对我们的MainViewModel的影响。

namespace WpfApp.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private readonly ItemsContext _dogContext;
        private readonly ItemsContext _authorContext;

        public MainViewModel()
        {
            _dogContext = new ItemsContext(FetchDogs()) { DisplayMemberPath = nameof(Dog.Breed) };
            _authorContext = new ItemsContext(FetchAuthors()) { DisplayMemberPath = nameof(Author.Genre) };
        }

        private ItemsContext selectedContext;
        public ItemsContext SelectedContext
        {
            get { return selectedContext; }
            set
            {
                selectedContext = value;
                OnPropertyChanged();
            }
        }

        private bool dogChecked;
        public bool DogChecked
        {
            get { return dogChecked; }
            set
            {
                dogChecked = value;
                if(dogChecked) SelectedContext = _dogContext;
            }
        }

        private bool authorChecked;
        public bool AuthorChecked
        {
            get { return authorChecked; }
            set
            {
                authorChecked = value;
                if(authorChecked) SelectedContext = _authorContext;
            }
        }

        private static IEnumerable<IEntity> FetchDogs() =>
            new List<IEntity>
            {
                new Dog("Terrier", "Ralph"),
                new Dog("Beagle", "Eddy"),
                new Dog("Poodle", "Fifi")
            };

        private static IEnumerable<IEntity> FetchAuthors() =>
            new List<IEntity>
            {
                new Author("SciFi", "Bradbury"),
                new Author("RomCom", "James")
            };
    }
}

两个干净分离的流,每个流管理其自己的上下文。很明显,您可以轻松地将其扩展到任意数量的上下文,而不会互相干扰。现在,为了将上下文应用于我们的ItemsControl,我们有两个选项。我们可以子类化我们的Control或使用附加属性。由于更倾向于组合而非继承,这里是带有AP的类。

namespace WpfApp.Extensions
{
    public class Selector
    {
        public static ItemsContext GetContext(DependencyObject obj) => (ItemsContext)obj.GetValue(ContextProperty);
        public static void SetContext(DependencyObject obj, ItemsContext value) => obj.SetValue(ContextProperty, value);

        public static readonly DependencyProperty ContextProperty =
            DependencyProperty.RegisterAttached("Context", typeof(ItemsContext), typeof(Selector), new PropertyMetadata(null, OnItemsContextChanged));

        private static void OnItemsContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var selector = (System.Windows.Controls.Primitives.Selector)d;
            var ctx = (ItemsContext)e.NewValue;

            if (e.OldValue != null) // Clean up bindings from previous context, if any
            {
                BindingOperations.ClearBinding(selector, System.Windows.Controls.Primitives.Selector.SelectedItemProperty);
                BindingOperations.ClearBinding(selector, ItemsControl.ItemsSourceProperty);
                BindingOperations.ClearBinding(selector, ItemsControl.DisplayMemberPathProperty);
            }

            selector.SetBinding(System.Windows.Controls.Primitives.Selector.SelectedItemProperty, new Binding(nameof(ItemsContext.SelectedItem)) { Source = ctx, Mode = BindingMode.TwoWay });
            selector.SetBinding(ItemsControl.ItemsSourceProperty, new Binding(nameof(ItemsContext.Items)) { Source = ctx });
            selector.SetBinding(ItemsControl.DisplayMemberPathProperty, new Binding(nameof(ItemsContext.DisplayMemberPath)) { Source = ctx });
        }
    }
}

这涵盖了第2步和第3步。您可以根据需要进行微调。例如,我们将ItemsContext.DisplayMemberPath设置为非通知属性,因此您可以直接设置值,而无需通过绑定。

最后是视图,这里将它们结合在一起。

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:vm="clr-namespace:WpfApp.ViewModels"
        xmlns:ext="clr-namespace:WpfApp.Extensions"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterScreen">
    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <Style x:Key="SelectorStyle" TargetType="{x:Type Selector}">
            <Setter Property="Width" Value="150"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="Margin" Value="0,20"/>
        </Style>
    </Window.Resources>
    <StackPanel Margin="20">
        <RadioButton GroupName="Entities" Content="Dogs" IsChecked="{Binding DogChecked}" />
        <RadioButton GroupName="Entities" Content="Authors" IsChecked="{Binding AuthorChecked}" />
        <ComboBox ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
        <ListBox  ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
        <DataGrid ext:Selector.Context="{Binding SelectedContext}" Style="{StaticResource SelectorStyle}" />
    </StackPanel>
</Window>

Attached Property的酷之处在于我们是在抽象的Selector控件上编码,该控件是ItemsControl的直接子代。因此,不需要更改底层代码,我们也可以与ListBox和DataGrid共享上下文。

我喜欢这个方向。因为我已经有了许多属性之间的共享接口,所以我可以使用它。虽然我想复制粘贴你在这里得到的内容,只是为了看到它全部工作,但我遇到了一些小问题。ViewModelBase是什么?其次,不是很重要,但所有属性都缺少设置?我认为?FetchDogsFetchAuthors似乎也对某些语法不满意。(从未这样做过,但我想看看如何使用正确的语法运行)。最后,nameof似乎是未知的。我目前正在使用VS2010和.Net 4.0。 - Birdbuster
@Birdbuster,“FetchDogs”和“FetchAuthors”使用表达式主体定义来定义这些方法,https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator。您只需更改定义以使用“return List<IEntity>”而不是“=>”运算符即可。 “nameof”运算符是在c# 6.0中添加的,但我不确定是否有办法使其与.Net 4.0一起工作。如果您无法使用较新版本的.Net,则此答案可能是解决方案。https://dev59.com/010Z5IYBdhLWcg3wnBVS#31262225。我猜测“ViewModelBase”只是定义了“OnPropertyChanged”。 - Wes
@Birdbuster 很高兴你喜欢它!设置器并不是“缺失的”,我选择为模型类使用不可变对象,这只是我的个人偏好。我已将解决方案移植到.NET4,您可以在GitHub上找到它。我不再使用VS2010,但如果您遇到迁移问题,应该可以复制文件。 - Funk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接