首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用WinUI 3按钮在GridTemplateColumn.CellTemplate中使用MVVM命令

使用WinUI 3按钮在GridTemplateColumn.CellTemplate中使用MVVM命令
EN

Stack Overflow用户
提问于 2022-08-31 21:37:29
回答 1查看 43关注 0票数 0

将WinUI 3与最新版本的DevExpress一起使用。

我希望在CommandParameter中有一个带有DevExpress.WinUI.Grid属性的Button。应用程序中的所有内容都是一个页面,并遵循MVVM模式,并使用依赖项注入。单击按钮时不会执行该命令。至少我希望看到Button真正执行。

XAML

代码语言:javascript
运行
复制
<Page
    x:Class="CSA2.Views.SearchUserPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CSA2.Views"
    xmlns:vm="using:CSA2.ViewModels"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:dxe="using:DevExpress.WinUI.Editors"
    xmlns:grid="using:DevExpress.WinUI.Grid"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    xmlns:ic="using:Microsoft.Xaml.Interactions.Core"
    mc:Ignorable="d">
    <StackPanel Orientation="Vertical" x:Name="ContentArea"
                Margin="{StaticResource SmallTopBottomMargin}">
        <ScrollViewer Height="450" ZoomMode="Disabled" VerticalScrollBarVisibility="Auto" VerticalScrollMode="Auto">
            <StackPanel Margin="0 0 10 0">
                <TextBlock x:Uid="SearchUser" Style="{ThemeResource SubtitleTextBlockStyle}"/>
                <Grid x:Name="userGrid" DataContext="{x:Bind ViewModel}">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <StackPanel>
                        <Grid HorizontalAlignment="Left">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <TextBlock x:Uid="UserNameText"
                                       Grid.Row="0"
                                       Grid.Column="0"
                                       VerticalAlignment="Center"
                                       Margin="5 0 5 0"/>
                            <dxe:TextEdit x:Uid="UserNameNullText"
                                          Grid.Row="0"
                                          Grid.Column="1"
                                          Margin="0 0 5 0"
                                          Width="200"
                                          Text="{x:Bind ViewModel.UserName, Mode=TwoWay}"/>
                            <TextBlock Grid.Row="0" x:Uid="UserEmailText"
                                       Grid.Column="2"
                                       VerticalAlignment="Center"
                                       Margin="0 0 5 0"/>
                            <dxe:TextEdit x:Uid="UserEmailNullText"
                                          Grid.Row="0"
                                          Grid.Column="3"
                                          Width="200"
                                          Text="{x:Bind ViewModel.UserEmail, Mode= TwoWay}"/>
                            <TextBlock x:Uid="UserRoleText"
                                       Grid.Row="0"
                                       Grid.Column="4"
                                       VerticalAlignment="Center"
                                       Margin="5 0 5 0"/>
                            <Button Grid.Row="0"
                                    Grid.Column="5"
                                    Margin="0 0 0 0" HorizontalAlignment="Stretch">
                                <StackPanel>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="Select"
                                                   Margin="0 0 10 0" />
                                        <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE70D;"/>
                                    </StackPanel>
                                </StackPanel>
                                <Button.Flyout>
                                    <Flyout Placement="Bottom">
                                        <StackPanel Orientation="Vertical">
                                            <ListView x:Name="UserRoles" ItemsSource="{x:Bind ViewModel.UserRoles, Mode=OneWay}"
                                                      SelectionMode="Multiple"
                                                      VerticalContentAlignment="Top"
                                                      ScrollViewer.IsVerticalRailEnabled="True"
                                                      ScrollViewer.VerticalScrollBarVisibility="Visible">
                                                <i:Interaction.Behaviors>
                                                    <ic:EventTriggerBehavior EventName="SelectionChanged">
                                                        <ic:InvokeCommandAction
                                                            Command="{x:Bind ViewModel.SelectedUserRolesCommand}"
                                                            CommandParameter="{x:Bind UserRoles.SelectedItems,Mode=OneWay}"/>
                                                    </ic:EventTriggerBehavior>
                                                </i:Interaction.Behaviors>
                                            </ListView>
                                        </StackPanel>
                                    </Flyout>
                                </Button.Flyout>
                            </Button>
                            <Button Grid.Row="0"
                                    Grid.Column="6"
                                    Margin="5 0 0 0"
                                    Command="{x:Bind ViewModel.SearchCommand}">
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock x:Uid="SearchButtonText"
                                               Margin="0 0 10 0" />
                                    <SymbolIcon Symbol="Zoom"/>
                                </StackPanel>
                            </Button>
                            <Button Grid.Row="1"
                                    Grid.Column="5"
                                    Command="{x:Bind ViewModel.AddUserCommand}">
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock x:Uid="AddButtonText" Margin="0 0 20 0"/>
                                    <SymbolIcon Symbol="AddFriend"/>
                                </StackPanel>
                            </Button>
                            <Button Grid.Row="1"
                                    Grid.Column="6"
                                    Margin="5 0 0 0"
                                    Command="{x:Bind ViewModel.ClearCommand}">
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock x:Uid="ClearButtonText" Margin="0 0 20 0"/>
                                    <SymbolIcon Symbol="Refresh"/>
                                </StackPanel>
                            </Button>
                        </Grid>
                    </StackPanel>
                    <Grid Grid.Row="1" Margin="0 5 0 5">
                        <grid:GridControl ItemsSource="{x:Bind ViewModel.Source, Mode = OneWay}"
                                          AutoGenerateColumns="False">
                            <grid:GridControl.Columns>
                                <grid:GridTextColumn FieldName="UserName" Header="User Name"/>
                                <grid:GridTextColumn FieldName="UserEmail" Header="User Email"/>
                                <grid:GridCheckBoxColumn FieldName="UserActiveIndicator" Header="User Status" />
                                <grid:GridDateColumn FieldName="RecordCreated" Header="Date Created"/>
                                <grid:GridDateColumn FieldName="RecordModified" Header="Date Modified"/>
                                <grid:GridTemplateColumn
                                    Header="Edit"
                                    HeaderHorizontalContentAlignment="Center"
                                    FixedWidth="True"
                                    Width="81">
                                    <grid:GridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <Button Command="{Binding DataContext.EditUserCommand, ElementName=userGrid}">
                                                <SymbolIcon Symbol="Edit"/>
                                            </Button>
                                        </DataTemplate>
                                    </grid:GridTemplateColumn.CellTemplate>
                                </grid:GridTemplateColumn>
                            </grid:GridControl.Columns>
                        </grid:GridControl>
                    </Grid>
                    <Expander Grid.Row="2" Margin="0 10 0 5"
                              HorizontalContentAlignment="Stretch"
                              HorizontalAlignment="Stretch">
                        <Expander.Header><TextBlock Text="Dashboard View"/>
                        </Expander.Header>
                        <Expander.Content>
                            <TabView SelectedIndex="0" MinHeight="275" TabItemsSource="{x:Bind ViewModel.TabItems}"
                                     IsAddTabButtonVisible="False">
                                <TabView.TabItemTemplate>
                                    <DataTemplate>
                                        <TabViewItem Header="{Binding Header}" IsClosable="False">
                                            <TextBlock Text="{Binding Detail}" />
                                        </TabViewItem>
                                    </DataTemplate>
                                </TabView.TabItemTemplate>
                            </TabView>
                        </Expander.Content>
                    </Expander>
                </Grid>
            </StackPanel>
        </ScrollViewer>
    </StackPanel>
</Page>

ViewModel

代码语言:javascript
运行
复制
using System.Collections.ObjectModel;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CSA2.Contracts.Services;
using CSA2.Contracts.ViewModels;
using CSA2.Core.Contracts.Services;
using CSA2.Models;

namespace CSA2.ViewModels;

public class SearchUserViewModel : ObservableRecipient, INavigationAware
{
    private readonly INavigationService _navigationService;
    private readonly IUserDataService _userDataService;

    private string? _searchText;

    private IList<object>? _selectedUserRoles;
    private List<User> _userDataStore;
    private string? _userEmail;
    private string? _userName;

    private List<UserRole> _userRoles;
    private List<UserRole> _userRolesStore;

    public SearchUserViewModel(IUserDataService userDataService, INavigationService navigationService)
    {
        _selectedUserRoles = new List<object>();
        _userDataService = userDataService;
        _navigationService = navigationService;
        _userRoles = new List<UserRole>();
        _userRolesStore = new List<UserRole>();
        TabItems = new ObservableCollection<ObservableObject>();
        SearchCommand = new RelayCommand(Handle_SearchUsers);
        ClearCommand = new RelayCommand(Handle_ClearData);
        SelectedUserRolesCommand = new RelayCommand<object>(Handle_SelectedUserRoles);
        AddUserCommand = new RelayCommand(Handle_AddUser);
        EditUserCommand = new RelayCommand(Handle_EditUser);
        TabItems.Add(new DetailTabViewModel("Tab1"));
        TabItems.Add(new DetailTabViewModel("Tab2"));
        TabItems.Add(new DetailTabViewModel("Tab3"));
    }

    public ICommand SearchCommand
    {
        get;
    }

    public ICommand ClearCommand
    {
        get;
    }

    public ICommand SelectedUserRolesCommand
    {
        get;
        set;
    }

    public ICommand AddUserCommand
    {
        get;
        set;
    }

    public ICommand EditUserCommand
    {
        get;
        set;
    }

    public ObservableCollection<User> Source
    {
        get;
        set;
    } = new();

    public List<UserRole> SelectedUserRoles
    {
        get;
        set;
    } = new();

    public string? SearchText
    {
        get => _searchText;
        set => SetProperty(ref _searchText, value);
    }

    public List<UserRole> UserRoles
    {
        get => _userRoles;
        set => SetProperty(ref _userRoles, value);
    }

    public string? UserEmail
    {
        get => _userEmail;
        set => SetProperty(ref _userEmail, value);
    }

    public string? UserName
    {
        get => _userName;
        set => SetProperty(ref _userName, value);
    }

    public async void OnNavigatedTo(object parameter)
    {
        var data = await _userDataService.GetUserRoleData<List<UserRole>>();

        _userRolesStore = new List<UserRole>
        {
            new() { UserRoleDescription = "Super User", UserRoleId = 1 },
            new() { UserRoleDescription = "RS User", UserRoleId = 2 }
        };
        Source.Clear();
        UserRoles = _userRolesStore;
        _userDataStore = GetUsers();
        SearchUsers();
    }

    public void OnNavigatedFrom()
    {
    }

    private void Handle_EditUser()
    {
        var poo = 1;
    }

    private void Handle_SelectedUserRoles(object? obj)
    {
        if (obj != null)
        {
            _selectedUserRoles = obj as IList<object>;

            if (_selectedUserRoles != null && _selectedUserRoles.Any())
            {
                ProcessSelectedFlyoutItems(_selectedUserRoles);
            }
        }
    }

    private void ProcessSelectedFlyoutItems(IList<object>? selectedItems)
    {
        if (selectedItems != null)
        {
            foreach (var item in selectedItems)
            {
                if (item is UserRole userRole)
                {
                    if (!SelectedUserRoles.Contains(item))
                    {
                        SelectedUserRoles.Add(userRole);
                    }
                }
            }
        }
    }

    private void Handle_ClearData() => Clear();

    private void Clear()
    {
        SearchText = string.Empty;
        UserName = string.Empty;
        UserEmail = string.Empty;
        Source.Clear();
        _selectedUserRoles?.Clear();
        SelectedUserRoles?.Clear();
    }

    private void Handle_SearchUsers() => SearchUsers();

    private void SearchUsers()
    {
        var userRoles = SelectedUserRoles;
        List<User> selectedUsers;
        var users = _userDataStore;
        if (userRoles.Any())
        {
            selectedUsers = users.Where(u => userRoles.All(ur => u.UserRoles.All(ur2 => ur2 == ur.UserRoleId)))
                .ToList();
        }
        else
        {
            selectedUsers = _userDataStore;
        }


        foreach (var user in selectedUsers)
        {
            Source.Add(user);
        }
    }

    private List<User> GetUsers()
    {
        var users = new List<User>
        {
            new()
            {
                UserId = 1,
                UserName = "Joe Smith",
                UserEmail = "joesmith@company.com",
                Departments = new List<int>(),
                RecordCreated = DateTime.Today,
                RecordModified = DateTime.Today,
                UserRoles = new List<int> { 1 },
                UserActiveIndicator = true
            },
            new()
            {
                UserId = 2,
                UserName = "Mary Lamb",
                UserEmail = "marylamb@company.com",
                Departments = new List<int>(),
                RecordCreated = DateTime.Today,
                RecordModified = DateTime.Today,
                UserRoles = new List<int> { 1 },
                UserActiveIndicator = true
            },
            new()
            {
                UserId = 3,
                UserName = "Sam Iam",
                UserEmail = "SamIam@company.com",
                Departments = new List<int>(),
                RecordCreated = DateTime.Today,
                RecordModified = DateTime.Today,
                UserRoles = new List<int> { 1 },
                UserActiveIndicator = true
            },
            new()
            {
                UserId = 4,
                UserName = "Will Row",
                UserEmail = "WillRow@company.com",
                Departments = new List<int>(),
                RecordCreated = DateTime.Today,
                RecordModified = DateTime.Today,
                UserRoles = new List<int> { 1 },
                UserActiveIndicator = true
            },
            new()
            {
                UserId = 5,
                UserName = "LoeSee",
                UserEmail = "LoeSeew@company.com",
                Departments = new List<int>(),
                RecordCreated = DateTime.Today,
                RecordModified = DateTime.Today,
                UserRoles = new List<int> { 1 },
                UserActiveIndicator = true
            },
            new()
            {
                UserId = 6,
                UserName = "MeeToo",
                UserEmail = "MeeToo@company.com",
                Departments = new List<int>(),
                RecordCreated = DateTime.Today,
                RecordModified = DateTime.Today,
                UserRoles = new List<int> { 1 },
                UserActiveIndicator = true
            },
            new()
            {
                UserId = 7,
                UserName = "YeeHaa",
                UserEmail = "YeeHaa@company.com",
                Departments = new List<int>(),
                RecordCreated = DateTime.Today,
                RecordModified = DateTime.Today,
                UserRoles = new List<int> { 2 },
                UserActiveIndicator = true
            }
        };
        return users;
    }

    private void Handle_AddUser() => _navigationService.NavigateTo(typeof(AddUserViewModel).FullName!);
    private ObservableCollection<ObservableObject> tabItems;
    public ObservableCollection<ObservableObject> TabItems
    {
        get => tabItems; set => SetProperty(ref tabItems, value);
    }
}
EN

回答 1

Stack Overflow用户

发布于 2022-09-01 01:30:15

你应该试试这个。

  1. 给您的页面命名(前)。“ThisPage”(

)

代码语言:javascript
运行
复制
<Page x:Name="ThisPage" />

  1. 使用页面的名称绑定按钮命令.

代码语言:javascript
运行
复制
<Button Command="{Binding ElementName=ThisPage, Path=ViewModel.EditUserCommand}" />

顺便说一句,由于您使用的是CommunityTookit.Mvvm,,所以您可以像这样简化ViewModel代码。

代码语言:javascript
运行
复制
// You need to make your class "partial".
public partial class SearchUserViewModel : ObservableRecipient, INavigationAware
{
    [RelayCommand]
    // An "EditUserCommand" command will be auto-generated.
    private void EditUser()
    {
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73562154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档