wpf 使用MVVM Communitytoolkit通过RelayCommand更改初始化按钮列表的属性

5cnsuln7  于 2023-04-22  发布在  其他
关注(0)|答案(2)|浏览(270)

我有WPF应用程序与。NETCore 7和当它加载我有视图和视图模型
我使用ViewModel中的代码生成一个按钮列表,如下所示

public partial class DataViewModel : ObservableObject, INavigationAware
    {
        private bool _isInitialized = false;

        [ObservableProperty]
        private ObservableCollection<Scene> _scenes;

        public void OnNavigatedTo()
        {
            if (!_isInitialized)
                InitializeViewModel();
        }

        public void OnNavigatedFrom()
        {
        }

        private void InitializeViewModel()
        {
            var scenesCollection = new ObservableCollection<Scene>();

            for (int i = 0; i < 20; i++)
            {
                string name = "Scene " + (i + 1);
                var scene = new Scene
                {
                    Name = name,
                    Color = new SolidColorBrush(Color.FromArgb(200, 231, 129, 4)),
                    Icon = SymbolRegular.Play48,
                    IsPlaying = false
                };
                scene.PlayStopCommand = new RelayCommand(() => PlayStop(scene));
                scenesCollection.Add(scene);
            }

            Scenes = scenesCollection;

            _isInitialized = true;
        }

        [RelayCommand]
        public void PlayStop(Scene scene)
        {
            var random = new Random();
            if (scene.IsPlaying)
            {
                scene.Icon = SymbolRegular.Play48;
                scene.IsPlaying = false;
            }
            else
            {
                scene.Icon = SymbolRegular.Pause48; // Change the icon to the desired value
                scene.IsPlaying = true;
            }
            scene.Color = new SolidColorBrush(Color.FromArgb(
                (byte)200,
                (byte)random.Next(0, 250),
                (byte)random.Next(0, 250),
                (byte)random.Next(0, 250)));
        }
    }

场景结构如下

public struct Scene
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public Brush Color { get; set; }

        public RelayCommand PlayStopCommand { get; set; }

        public SymbolRegular Icon { get; set; }

        public bool IsPlaying { get; set; }
    }

XMAL码

<ui:VirtualizingItemsControl
            Foreground="{DynamicResource TextFillColorSecondaryBrush}"
            ItemsSource="{Binding ViewModel.Scenes, Mode=OneWay}"
            VirtualizingPanel.CacheLengthUnit="Item">
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="{x:Type models:Scene}">
                    <ui:Button
                        x:Name="buttin"
                        Width="600"
                        Height="50"
                        Margin="2"
                        Padding="0"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Appearance="Secondary"
                        Background="{Binding Color, Mode=OneWay}"
                        Command="{Binding PlayStopCommand}"
                        Content="{Binding Name, Mode=TwoWay}"
                        FontFamily="Arial"
                        FontSize="25"
                        FontWeight="Bold"
                        Foreground="White"
                        Icon="{Binding Icon, Mode=TwoWay}"
                        IconFilled="True" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ui:VirtualizingItemsControl>

按钮初始化正确,但是,当我点击任何按钮没有任何变化。
我甚至尝试使用断点,我发现每次我调用PlayStopCommand场景时,IsPlaying总是false,并且不会改变,所以这意味着代码以某种方式改变了另一个临时场景,我不确定。

rmbxnbpk

rmbxnbpk1#

您的问题在于用于识别已单击的按钮/场景的机制:
scene.PlayStopCommand = new RelayCommand(() => PlayStop(scene));中,本地变量scene有一个闭包。这意味着当执行命令时,scene的实际值(在那个时刻)被使用。但是在那个时刻scene不再存在:它被局部地限定到for循环迭代。
所以你需要找到另一种方法来找到被点击的确切按钮。有一个简单的方法来做到这一点。例如:
1.重构命令以接受字符串参数:
public RelayCommand<string> PlayStopCommand { get; set; }
1.将场景的Name属性作为CommandParameter传递:

Command="{Binding PlayStopCommand}"
 CommandParameter="{Binding Name"

1.重构命令实现以接受名称作为参数(并从中识别单击的按钮):

scene.PlayStopCommand = new RelayCommand((name) => PlayStop(name));

使用适配的PlayStop方法:

public void PlayStop(string name)
   {
      // find the right scene in the _scenes collection
      var scene = _scenes.First((s) => s.Name == name); 
      
      var random = new Random();
      if (scene.IsPlaying)
      ...

最后:如果你希望场景属性中的任何更改都能反映在你的UI中,你需要通知视图更改(你的_scenes集合是可观察的,但场景的属性不在你发布的代码中)。
编辑:最后一部分是在你自己的回答中处理的。。

cuxqih21

cuxqih212#

我最终将Scene结构改为ObservableObject

public partial class Scene : ObservableObject
{
    [ObservableProperty]
    public int _iD;

    [ObservableProperty]
    public string? name;

    [ObservableProperty]
    public Brush? color;

    [ObservableProperty]
    public RelayCommand? playStopCommand;

    [ObservableProperty]
    public SymbolRegular icon;

    [ObservableProperty]
    public bool isPlaying;
}

相关问题