English 中文(简体)
采用MVLT 改变纽芬兰语或背景的社区工具
原标题:Using MVVM Communitytoolkit to change button foreground or background
  • 时间:2023-08-09 22:46:38
  •  标签:
  • c#
  • wpf
  • mvvm

I m new to WPF and CommunityToolkit.Mvvm. I m starting to build a sample project based on an WinForm design. The part I m stuck on is setting a RadioButton Foreground and/or Background. I was told and given instruction to use "Styles" to do this. XAML looks like this for the Window.Resources:

<Window.Resources>
    <Style x:Key="GroupToggleStyle" TargetType="RadioButton" 
           BasedOn="{StaticResource {x:Type ToggleButton}}">
        <Setter Property="Foreground" Value="Blue"/>
        <Style.Triggers>
                <DataTrigger Binding="{Binding IsErrorProcess, RelativeSource={RelativeSource Self}}" 
                         Value="True">
                <DataTrigger.Setters>
                    <Setter Property="Foreground" Value="Red"/>
                </DataTrigger.Setters>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

我的XAML无线电台编码:

<RadioButton GroupName="btnErrorLog"
             Command="{Binding OpenError}"
             Content="{Binding ErrorText}"
             Width="80"
             IsEnabled="{Binding IsProcessingData}"
             Margin="5" HorizontalAlignment="Left"
             VerticalAlignment="Center"
             Style="{StaticResource GroupToggleStyle}" />

This will change the text/content of the RadioButton when clicked to "RED". However I m tring to get the button foreground (at this time) to change to "Red" only when public property "IsErrorProcess" changes to "true". I believe I have the binding correct on both "style" and "radiobutton".

我的问题是这个问题。 当我确定IsErrorProcess为真实情况时,我无法说明如何为原地划定界线。

My MainWindowViewModel.cs代码:(我必须删除真正的客户数据档案)

    using CommunityToolkit.Mvvm.ComponentModel;
    using CommunityToolkit.Mvvm.Input;
    using CommunityToolkit.Mvvm.Messaging;
    using ImporterMessaging;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Threading.Tasks;
    using System.Windows.Documents;
    using System.Windows.Media;
    using Wpsi.CorrelDataImporter;


    namespace CorelImporter
    {
        public class MainWindowViewModel : ObservableRecipient
        {
        #region Variables/Fields
        private string _importFileName = string.Empty;
        private int _digitLength;
        private string _filterString = string.Empty;
        private List<CorrelUserRecord> _correlUserData = new List<CorrelUserRecord>();
        private List<string> _afterData = new List<string>();
        private List<string> _beforeData = new List<string>();
        private ObservableObject _count;
        private string _processingText;
        private bool _isProcessingData;
        private string _statusMessage;
                private string _errorText;
                private bool _isErrorProcess;
        public Brush btnErrorColor;
        #endregion

        #region RelayCommands
        public AsyncRelayCommand ProcessData { get; set; }
        public AsyncRelayCommand OpenError { get; set; }
        #endregion

        #region Properties
        public string ImportFileName
        {
            get => _importFileName;
            set
            {
                if (_importFileName == value)
                {
                    return;
                }
                _importFileName = value;
                OnPropertyChanged(nameof(ImportFileName));
            }
        }
        public string FilterString
        {
            get => _filterString;
            set
            {
                if (_filterString == value)
                {
                    return;
                }
                _filterString = value;
                OnPropertyChanged(nameof(FilterString));
            }
        }
        public List<CorrelUserRecord> CorrelUserData
        {
            get => _correlUserData;
            set
            {
                if (_correlUserData == value)
                {
                    return;
                }
                _correlUserData = value;
                OnPropertyChanged(nameof(CorrelUserData));
            }
        }
        public List<string> AfterData
        {
            get => _afterData;
            set
            {
                if (_afterData == value)
                {
                    return;
                }
                _afterData = value;
                OnPropertyChanged(nameof(AfterData));
            }
        }
        public List<string> BeforeData
        {
            get => _beforeData;
            set
            {
                if (_beforeData == value)
                {
                    return;
                }
                _beforeData = value;
                OnPropertyChanged(nameof(BeforeData));
            }
        }
        public int DigitLength
        {
            get => _digitLength;
            set
            {
                if (_digitLength == value)
                {
                    return;
                }
                _digitLength = value;
                OnPropertyChanged(nameof(DigitLength));
            }
        }
        public ObservableObject Count
        {
            get => _count;
            set
            {
                if (_count == value)
                    return;
                _count = value;
                OnPropertyChanged(nameof(Count));

            }
        }
        public bool IsChecked
        {
            get => Globals.IsChecked;
            set
            {
                if (Globals.IsChecked == value)
                    return;
                Globals.IsChecked = value;
                OnPropertyChanged(nameof(IsChecked));
            }
        }
        public bool IsProcessingData
        {
            get => _isProcessingData;
            set
            {
                if (_isProcessingData == value)
                    return;
                _isProcessingData = value;
                OnPropertyChanged(nameof(IsProcessingData));
            }
        }
        public string ProcessingText
        {
            get => _processingText;
            set
            {
                if (_processingText== value)
                    return;
                _processingText = value;
                OnPropertyChanged(nameof(ProcessingText));
            }
        }
        public string StatusMessage
        {
            get => _statusMessage;
            set
            {
                if (_statusMessage == value)
                    return;
                _statusMessage = value;
                OnPropertyChanged(nameof(StatusMessage));
            }
        }
        public string ErrorText
        {
            get => _errorText;
            set
            {
                if (_errorText == value)
                    return;
                _errorText = value;
                OnPropertyChanged(nameof(ErrorText));
            }
        }
        public bool IsErrorProcess
        {
            get => _isErrorProcess;
            set
            {
                if (_isErrorProcess == value)
                    return;
                _isErrorProcess = value;
                OnPropertyChanged(nameof(IsErrorProcess));
                btnErrorColor = Brushes.Red;
                OnPropertyChanged(nameof(btnErrorColor));
            }
        }
        #endregion

        public MainWindowViewModel()
        {
            ImportFileName = Path.Combine(CorrelDataImporter.ImportExportPath, @"");
            DigitLength = 11;
            FilterString = "+1214648";
            AfterData.Add("AFTER NOT DATA LOADED");
            BeforeData.Add("BEFORE NOT DATA LOADED");
            ProcessingText = "Click To Process";
            ErrorText = "Error Log";
            IsProcessingData = true;
            IsErrorProcess = true;
            StatusMessage = string.Empty;
            //Count = 0.ToString();

            ProcessData = new AsyncRelayCommand(OnProcessDataExecute, () => true);
            OpenError = new AsyncRelayCommand(OnOpenErrorExecute, () => true);

            // Register a message in some module
            WeakReferenceMessenger.Default.Register<CorrelImporterStatusMessages>(this, (r, m) =>
            {
                // Handle the message here, with r being the recipient and m being the
                // input message. Using the recipient passed as input makes it so that
                // the lambda expression doesn t capture "this", improving performance.
                UpdateStatusMessage(m.Value);
            });
            WeakReferenceMessenger.Default.Register<UpdateBeforeDataList>(this, (r, m) =>
            {
                // Handle the message here, with r being the recipient and m being the
                // input message. Using the recipient passed as input makes it so that
                // the lambda expression doesn t capture "this", improving performance.
                UpdateBeforeList(m.Value);
            });
            WeakReferenceMessenger.Default.Register<UpdateAfterDataList>(this, (r, m) =>
            {
                // Handle the message here, with r being the recipient and m being the
                // input message. Using the recipient passed as input makes it so that
                // the lambda expression doesn t capture "this", improving performance.
                UpdateAfterList(m.Value);
            });
            //WeakReferenceMessenger.Default.Register<ErrorButtonColor>(this, (r, m) =>
            //{
            //  // Handle the message here, with r being the recipient and m being the
            //  // input message. Using the recipient passed as input makes it so that
            //  // the lambda expression doesn t capture "this", improving performance.
            //  IsErrorProcess(m.Value);
            //});
        }
        private void UpdateBeforeList(List<string> value)
        {
            BeforeData = value;
        }
        private void UpdateAfterList(List<string> value)
        {
            AfterData = value;
        }
        private void UpdateStatusMessage(string statusMessage)
        {
            StatusMessage = statusMessage;
        }
        //private void ErrorButtonColor(System.Drawing.Color value)
        //{
        //  IsErrorProcess.f = Color.Red;
        //}
        private async Task OnProcessDataExecute()
        {
            if (Globals.IsChecked == true)
            {
                string sDeleteFile = $"{Globals.sAPPPath}\{Globals.sApplicationName}" + ".log";
                if (File.Exists(sDeleteFile))
                    File.Delete(sDeleteFile);
                
                IsChecked = false;
            }

            IsProcessingData = false;
            ProcessingText = "Processing Data...";

            await LoadCorrelData();

            WeakReferenceMessenger.Default.Send(new CorrelImporterStatusMessages($"Process completed."));

            IsProcessingData = true;
            ProcessingText = "Click To Process";

            btnErrorColor = Brushes.Black;
            if (Globals.bErrorOn == true)
            {
                IsErrorProcess = true;
                btnErrorColor = Brushes.Red;
            }
        }

        private async Task OnOpenErrorExecute()
        {
            if(Globals.bErrorOn == true) 
            {
                IsErrorProcess= true;
                Process myProcess = new Process();
                string sGet = $"{Globals.sAPPPath}\{Globals.sApplicationName}" + ".log";
                Process.Start("notepad.exe", sGet);

            }
        }
        public async Task LoadCorrelData()
        {
                    CorrelUserData = await CorrelDataImporter.ProcessCorrelData(Path.Combine(CorrelDataImporter.ImportExportPath, @""));

            //This program is much like Command Project but in WPF
            await CorrelDataImporter.ProcessAfterList(CorrelUserData, FilterString, DigitLength);
        }
    }
}

Using "CommunityToolkit.Mvvm.Messaging.Messages". It was also suggested I could use this method to call the radio button style changed but I can t work it out. Real don t know what I m doing without a working sample. I m still not sure when "Styles" are needed and not. help here would be appreciated as well.

A working solution would be appreciated.

问题回答

页: 1 Self}是因为sol系指RadioButton in this case and IsErrorProcess,见“你的看法”,而不是载于“RadioButton。

这是我操作的最低限度代码(更新RadioButton sForeground)。

<Window.Resources>
    <Style TargetType="RadioButton">
        <Setter Property="Foreground" Value="Blue" />
        <Style.Triggers>
            <DataTrigger
                Binding="{Binding IsErrorProcess}"
                Value="True">
                <DataTrigger.Setters>
                    <Setter Property="Foreground" Value="Red" />
                </DataTrigger.Setters>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<StackPanel>
    <Button
        Command="{Binding TestCommand}"
        Content="Test" />
    <RadioButton Content="{Binding ErrorText}" />
</StackPanel>
public partial class MainWindowViewModel : ObservableObject
{
    [ObservableProperty]
    private bool isErrorProcess;

    [ObservableProperty]
    private string? errorText;

    [RelayCommand]
    private void Test()
    {
        IsErrorProcess = IsErrorProcess is false;
        ErrorText = IsErrorProcess is true
            ? "Error text"
            : string.Empty;
    }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签