在 WPF 中使用 MVVM Light 框架进行赋值 ToggleButton 的操作,首先需要创建一个 ViewModel 类,然后在 XAML 中绑定 ViewModel 的属性到 ToggleButton 的 IsChecked 属性上。

ViewModel 类示例:

using GalaSoft.MvvmLight;

namespace WpfApp.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        private bool _isToggleButtonChecked;

        public bool IsToggleButtonChecked
        {
            get { return _isToggleButtonChecked; }
            set
            {
                _isToggleButtonChecked = value;
                RaisePropertyChanged(nameof(IsToggleButtonChecked));
            }
        }
    }
}

在 XAML 中,首先引入 MVVM Light 的命名空间,并设置 DataContext 为 ViewModel 的实例。然后在 ToggleButton 的 IsChecked 属性中绑定 ViewModel 的 IsToggleButtonChecked 属性。

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp"
        xmlns:vm="clr-namespace:WpfApp.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <ToggleButton Content="Toggle Button" 
                      IsChecked="{Binding IsToggleButtonChecked}"/>
    </Grid>
</Window>

这样,当 ViewModel 的 IsToggleButtonChecked 属性发生变化时,ToggleButton 的 IsChecked 属性也会随之变化。

WPF MVVM Light: ToggleButton 绑定与数据双向同步

原文地址: https://www.cveoy.top/t/topic/onoM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录