C# WPF - Привязка команды не работает - PullRequest
0 голосов
/ 26 марта 2020

Добрый день,

Я хотел бы задать вопрос о том, как правильно связать RelayCommand UpdateUserCommand () в кнопке переключения. Пожалуйста, смотрите мой код ниже

<UserControl x:Class="istock.View.UserMasterList"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
         xmlns:local="clr-namespace:istock.View"
         mc:Ignorable="d" 
         MinHeight="450" Width="Auto" MinWidth="1024" FontFamily="Segoe UI LIght"> 
<Grid>
    <Border Padding="30 15">
        <StackPanel>
            <Grid>
                <TextBlock Text="User Management" FontSize="20" HorizontalAlignment="Left" Width="Auto" />
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Width="Auto">
                    <Button x:Name="btnNew" Foreground="#FFFF">
                        <StackPanel Orientation="Horizontal">
                            <materialDesign:PackIcon Kind="PlusBoxOutline" Margin="0 5" />
                            <TextBlock Text="New User"  Margin="5 3 5 0" />
                        </StackPanel>
                    </Button>
                </StackPanel>
            </Grid>
            <ListView ItemsSource="{Binding Path = UserMasterListProp}">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="ID" Width="auto" DisplayMemberBinding="{Binding Path = Id}"></GridViewColumn>
                        <GridViewColumn Header="Username" Width="120" DisplayMemberBinding="{Binding Path = Username}"></GridViewColumn>
                        <GridViewColumn Header="Firstname" Width="120" DisplayMemberBinding="{Binding Path = Firstname}"></GridViewColumn>
                        <GridViewColumn Header="Middlename" Width="120" DisplayMemberBinding="{Binding Path = Middlename}"></GridViewColumn>
                        <GridViewColumn Header="Lastname" Width="120" DisplayMemberBinding="{Binding Path = Lastname}"></GridViewColumn>
                        <GridViewColumn Header="Role" Width="100" DisplayMemberBinding="{Binding Path = Role}"></GridViewColumn>
                        <GridViewColumn Header="Activated">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <ToggleButton x:Name="tbtnActivated" Style="{DynamicResource MaterialDesignSwitchToggleButton}" IsChecked="{Binding Path = Activated}" Command="{Binding Path = UserViewModel.UpdateUserCommand}" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn Header="Locked">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <ToggleButton x:Name="tbtnLocked" Style="{DynamicResource MaterialDesignSwitchToggleButton}" IsChecked="{Binding Path = Locked}" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>
    </Border>
</Grid>

Вот мой код команды, который был инициализирован, и метод CanExecute () всегда верен.

        public class RelayCommand : ICommand
{
    private Action ExecuteCmd;
    public RelayCommand(Action paramAction)
    {
        this.ExecuteCmd = paramAction;
    }

   public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        this.ExecuteCmd();
    }
}

И вот мой код во ViewModel, который метод UpdateUser () будет запущен моим UpdateUserCommand ()

      #region Update Command and Method
    private RelayCommand updateUserCommand;

    public RelayCommand UpdateUserCommand
    {
        get { return updateUserCommand; }
    }

    public void UpdateUser()
    {
        try
        {
            var isExist = this.userService.ApplyService_FindByIdOrUsername(UserModel.Id, UserModel.Username);
            if(isExist == null)
            {
                var isUpdated = this.userService.ApplyService_Update(UserModel);
                if (isUpdated == true)
                {
                    this.Message = "Update sucesss.";
                    this.Populate_UserMasterList();
                }
            }
            else
            {
                this.Message = "Update failed. ID or Username already exist.";
                return;
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
            return;
        }
    }
    #endregion

Вот реализация контекста данных в коде позади пользовательского элемента управления

public partial class UserMasterList : UserControl
{
    public UserMasterList()
    {
        InitializeComponent();
        UserViewModel userViewModel = new UserViewModel();
        this.DataContext = userViewModel;
    }
}

Пожалуйста Помогите. Если когда-либо мой код сбивает с толку, я открыт для вопроса. Спасибо

1 Ответ

0 голосов
/ 26 марта 2020

Вы можете привязать к свойству родителя UserControl, используя {RelativeSource}:

<ToggleButton x:Name="tbtnActivated"
              Style="{DynamicResource MaterialDesignSwitchToggleButton}"      
              IsChecked="{Binding Activated}"
              Command="{Binding DataContext.UpdateUserCommand, 
                  RelativeSource={RelativeSource AncestorType=UserControl}}" />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...