单击“自定义控件”上的“更新属性”

时间:2018-12-30 19:03:28

标签: c# wpf mvvm custom-controls inputbinding

我正在使用WPF(尤其是MVVM模式),并且试图创建一个显示任务列表的简单应用程序。我创建了一个名为TaskListControl的自定义控件,该控件显示了一个名为TaskListItemControl的其他自定义控件的列表,每个自定义控件都有自己的ViewModel。

这里是TaskListItemControl模板,您可以在其中将{IsSelected设置为InputBindings的情况下看到Triggerstrue,它们会影响控件的外观:

<UserControl x:Class="CSB.Tasks.TaskListItemControl"
         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:local="clr-namespace:CSB.Tasks"
         mc:Ignorable="d"
         d:DesignHeight="70" 
         d:DesignWidth="400">

<!-- Custom control that represents a Task. -->
<UserControl.Resources>
    <!-- The control style. -->
    <Style x:Key="ContentStyle" TargetType="{x:Type ContentControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ContentControl}">

                    <Border x:Name="ContainerBorder" BorderBrush="{StaticResource LightVoidnessBrush}"
                            Background="{StaticResource VoidnessBrush}"
                            BorderThickness="1"
                            Margin="2">

                        <Border.InputBindings>
                            <MouseBinding MouseAction="LeftClick" Command="{Binding SelctTaskCommand}"/>
                        </Border.InputBindings>

                        <!-- The grid that contains the control. -->
                        <Grid Name="ContainerGrid" Background="Transparent">

                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>

                            <!-- Border representing the priority state of the Task:
                            The color is defined by a ValueConverter according to the PriorityLevel of the Task object. -->
                            <Border Grid.Column="0"
                                    Width="10"
                                    Background="{Binding Priority, Converter={local:PriorityLevelToRGBConverter}}">
                            </Border>

                            <!-- Border containing the Task's informations. -->
                            <Border Grid.Column="1" Padding="5">
                                <StackPanel>
                                    <!-- The title of the Task. -->
                                    <TextBlock Text="{Binding Title}" FontSize="{StaticResource TaskListItemTitleFontSize}" Foreground="{StaticResource DirtyWhiteBrush}"/>

                                    <!-- The customer the Taks refers to. -->
                                    <TextBlock Text="{Binding Customer}" Style="{StaticResource TaskListItemControlCustomerTextBlockStyle}"/>

                                    <!-- The description of the Task. -->
                                    <TextBlock Text="{Binding Description}"
                                               TextTrimming="WordEllipsis"
                                               Foreground="{StaticResource DirtyWhiteBrush}"/>
                                </StackPanel>
                            </Border>

                            <!-- Border that contains the controls for the Task management. -->
                            <Border Grid.Column="2"
                                    Padding="5">

                                <!-- Selection checkbox of the Task. -->
                                <CheckBox Grid.Column="2" VerticalAlignment="Center"/>
                            </Border>

                        </Grid>

                    </Border>

                    <!-- Template triggers. -->
                    <ControlTemplate.Triggers>

                        <DataTrigger Binding="{Binding IsSelected}" Value="True">
                            <Setter Property="Background" TargetName="ContainerBorder" Value="{StaticResource OverlayVoidnessBrush}"/>
                            <Setter Property="BorderBrush" TargetName="ContainerBorder" Value="{StaticResource PeterriverBrush}"/>
                        </DataTrigger>

                        <EventTrigger RoutedEvent="MouseEnter">
                            <BeginStoryboard>
                                <Storyboard>
                                    <ColorAnimation Duration="0:0:0:0" To="{StaticResource OverlayVoidness}" Storyboard.TargetName="ContainerGrid" Storyboard.TargetProperty="Background.Color"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>

                        <EventTrigger RoutedEvent="MouseLeave">
                            <BeginStoryboard>
                                <Storyboard>
                                    <ColorAnimation Duration="0:0:0:0" To="Transparent" Storyboard.TargetName="ContainerGrid" Storyboard.TargetProperty="Background.Color"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>

<!-- Content of the control: assignment of the DataContext for design-time testing. -->
<ContentControl d:DataContext="{x:Static local:TaskListItemDesignModel.Instance}" 
                Style="{StaticResource ContentStyle}"/>

这是TaskListItemViewModel,应在其中执行Action(所有PropertyChanged样板代码都在BaseViewModel类内部处理):

/// <summary>
/// The ViewModel for the <see cref="TaskListItemControl"/>.
/// </summary>
public class TaskListItemViewModel : BaseViewModel
{
    #region Public Properties

    /// <summary>
    /// Priority level of the task.
    /// </summary>
    public PriorityLevel Priority { get; set; }

    /// <summary>
    /// The name of the task.
    /// </summary>
    public string Title { get; set; }

    /// <summary>
    /// The customer the task refers to.
    /// </summary>
    public string Customer { get; set; }

    /// <summary>
    /// The description of the task.
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// True if the Task is the selected one in the task list.
    /// </summary>
    public bool IsSelected { get; set; }

    #endregion

    #region Commands

    /// <summary>
    /// The command fired whenever a task is selected.
    /// </summary>
    public ICommand SelectTaskCommand { get; set; }

    #endregion

    #region Constructor

    /// <summary>
    /// The <see cref="TaskListItemViewModel"/> default constructor.
    /// </summary>
    public TaskListItemViewModel()
    {
        // Initialize commands.
        // When the task is selected, IsSelected becomes true.
        // The command will do other stuff in the future.
        SelectTaskCommand = new RelayCommand(() => IsSelected = true);
    }

    #endregion
}

数据是通过绑定到TaskListControl控件的设计模型提供的,在该控件中,列表的每个项目的属性都进行了硬编码(该设计模型将被数据库替换,因为此类仅提供伪数据):

/// <summary>
/// The <see cref="TaskListControl"/> design model that provides dummy data for the XAML testing.
/// </summary>
public class TaskListDesignModel : TaskListViewModel
{
    #region Public Properties

    /// <summary>
    /// A single instance of the <see cref="TaskListDesignModel"/> class.
    /// </summary>
    public static TaskListDesignModel Instance => new TaskListDesignModel();

    #endregion

    #region Constructor

    /// <summary>
    /// The <see cref="TaskListDesignModel"/> default constructor that provides dummy data.
    /// </summary>
    public TaskListDesignModel()
    {
        Items = new ObservableCollection<TaskListItemViewModel>
        {
            new TaskListItemViewModel
            {
                Title = "Activity #1",
                Customer = "Internal",
                Description = "This is activity #1.",
                Priority = PriorityLevel.High,
                IsSelected = false
            },

            new TaskListItemViewModel
            {
                Title = "Activity #2",
                Customer = "Internal",
                Description = "This is activity #2.",
                Priority = PriorityLevel.High,
                IsSelected = false
            },

            new TaskListItemViewModel
            {
                Title = "Activity #3",
                Customer = "Internal",
                Description = "This is activity #3.",
                Priority = PriorityLevel.High,
                IsSelected = false
            },

            new TaskListItemViewModel
            {
                Title = "Activity #4",
                Customer = "Internal",
                Description = "This is activity #4.",
                Priority = PriorityLevel.Medium,
                IsSelected = false
            },

            new TaskListItemViewModel
            {
                Title = "Activity #5",
                Customer = "Internal",
                Description = "This is activity #5.",
                Priority = PriorityLevel.Medium,
                IsSelected = false
            },

            new TaskListItemViewModel
            {
                Title = "Activity #6",
                Customer = "Internal",
                Description = "This is activity #6.",
                Priority = PriorityLevel.Low,
                IsSelected = false
            }

        };
    }

    #endregion
}

结果如下: items_list

选择列表项后,我想做的是更新他的 IsSelected ViewModel中的属性,并通过 {{1} } ,但是当我单击一个项目时什么也没发生。

Here是指向整个项目的GitHub存储库的链接。

我想念什么?预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您应该解决这两个问题以解决选择问题:

1)我在您的TaskListItemControl内发现了一个错字: 第25行应为Command绑定上的“ Sel e ctTaskCommand”。 最后将调用该命令。

2)然后,在您的TaskListItemViewModel中,必须使属性引发PropertyChanged事件。我强烈建议您为所有ViewModel属性使用此功能。但是要解决您的问题,必须至少将其应用于IsSelected属性:

private bool isSelected;
public bool IsSelected 
{ 
  get => this.isSelected; 
  set 
  { 
    if (value.Equals(this.isSelected)
    {
      return;
    }

    this.isSelected = value;  
    OnPropertyChanged(); 
  }
}

这将传播对IsSelected的任何更改,因此DataTrigger可以按预期工作。

另一个建议是将PropertyChanged中的BaseViewModel发起人签名修改为:

public void OnPropertyChanged([CallerMemberName] string propertyName = null)

这样可以避免始终将属性名称作为参数传递。

如果您希望CheckBox反映选择状态并应用于撤消选择,只需将TwoWay绑定添加到其IsChecked属性:

<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}" />