C#UWP DataTemplate内存泄漏

时间:2018-08-16 11:53:06

标签: c# mvvm memory-leaks uwp datatemplate

我正在使用MVVM light创建我的第一个C#UWP桌面应用程序,并且在内存使用和DataTemplates方面存在小问题。 在Button.cs中,有一个ObservableCollection,它可能具有不同的对象(IExample),例如:圆形,正方形和其他... 根据该集合中的内容,应显示正确的UI。

My example application - animation - take a look at memory usage when changing button

这是我的代码:

Buttons.cs:

using GalaSoft.MvvmLight;
using System.Collections.ObjectModel;

namespace MvvmLight1.Model
{
    public class Button : ObservableObject
    {
        public string Name { get; set; }

        public const string InternalObjectsPropertyName = "InternalObjects";
        private ObservableCollection<IExample> _internalObjects = null;
        public ObservableCollection<IExample> InternalObjects
        {
            get
            {
                return _internalObjects;
            }

            set
            {
                if (_internalObjects == value)
                {
                    return;
                }

                _internalObjects = value;
                RaisePropertyChanged(InternalObjectsPropertyName);
            }
        }

        public Button()
        {
            InternalObjects = new ObservableCollection<IExample>();
        }
    }
}

MainPage.xaml:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="using:MvvmLight1"
  xmlns:ignore="http://www.galasoft.ch/ignore"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
  xmlns:core="using:Microsoft.Xaml.Interactions.Core"
  xmlns:local1="using:MvvmLight1.Model"
  x:Class="MvvmLight1.MainPage"
  mc:Ignorable="d ignore"
  DataContext="{Binding Main, Source={StaticResource Locator}}">
<Page.Resources>
    <!-- template for circle -->
    <DataTemplate x:Key="CircleTemplate">
        <StackPanel>
            <TextBlock Text="This is the template for circle..." Foreground="Crimson" HorizontalAlignment="Center"></TextBlock>
            <ColorPicker x:Name="myColorPicker" ColorSpectrumShape="Ring"/>
        </StackPanel>
    </DataTemplate>
    <!-- template for square -->
    <DataTemplate x:Key="SquareTemplate">
            <StackPanel>
                <TextBlock Text="This is the template for square..." Foreground="Green" HorizontalAlignment="Center"></TextBlock>
                <ColorPicker x:Name="myColorPicker" ColorSpectrumShape="Ring"/>
            </StackPanel>
    </DataTemplate>

    <local1:TemplateSelector x:Key="MySelector"
        CircleTemplate="{StaticResource CircleTemplate}"
        SquareTemplate="{StaticResource SquareTemplate}"
    />

</Page.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="2*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <!-- buttons -->
    <GridView ItemsSource="{Binding ButtonsList}" Grid.Row="0" SelectedItem="{Binding SelectedButton, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="x:String">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="250"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Name}" Foreground="Red" 
                       FontSize="15" Grid.Column="0" VerticalAlignment="Stretch" HorizontalAlignment="Center"/>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

    <!-- properties -->
    <ItemsControl ItemsSource="{Binding InternalObjects, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemTemplateSelector="{StaticResource MySelector}" DataContext="{Binding SelectedButton}" Grid.Column="1"></ItemsControl>
</Grid>

public class MainViewModel : ViewModelBase
{
    public const string ButtonsListPropertyName = "ButtonsList";
    private ObservableCollection<Button> _buttonsList = null;
    public ObservableCollection<Button> ButtonsList
    {
        get
        {
            return _buttonsList;
        }

        set
        {
            if (_buttonsList == value)
            {
                return;
            }

            _buttonsList = value;
            RaisePropertyChanged(ButtonsListPropertyName);
        }
    }

    public const string SelectedButtonPropertyName = "SelectedButton";
    private Button _selectedButton = null;
    public Button SelectedButton
    {
        get
        {
            return _selectedButton;
        }

        set
        {
            if (_selectedButton == value)
            {
                return;
            }

            _selectedButton = value;
            RaisePropertyChanged(SelectedButtonPropertyName);

        }
    }

    public MainViewModel()
    {
        ButtonsList = new ObservableCollection<Button>();

        // create new buttons
        for (var i = 0; i < 12; i++)
        {
            ButtonsList.Add(new Button());
        }

        // for few of them add circles...
        for (var i = 0; i < 3; i++)
        {
            ButtonsList[i].Name = "Button with Circle";
            ButtonsList[i].InternalObjects.Add(new Circles() { Name = "Circles" });
        }
        // for another add squares...
        for (var i = 3; i < 6; i++)
        {
            ButtonsList[i].Name = "Button with Squres";
            ButtonsList[i].InternalObjects.Add(new Squares() { Name = "Squares" });
        }
        // rest of them mixed...
        for (var i = 6; i < 12; i++)
        {
            ButtonsList[i].Name = "Button with Circles and Squres";

            ButtonsList[i].InternalObjects.Add(new Circles() { Name = "Circles" });
            ButtonsList[i].InternalObjects.Add(new Squares() { Name = "Squares" });
        }
    }


}

Circles.cs:

public class Circles : IExample
{
    public string Name { get; set; }
}

Squares.cs:

public class Squares : IExample
{
    public string Name { get; set; }
}

TemplateSelector.cs:

public class TemplateSelector : DataTemplateSelector
{
    public DataTemplate CircleTemplate { get; set; }
    public DataTemplate SquareTemplate { get; set; }
    protected override DataTemplate SelectTemplateCore(object item)
    {

        if (item.GetType() == typeof(Circles))
        {
            return CircleTemplate;
        }
        else if (item.GetType() == typeof(Squares))
        {
            return SquareTemplate;
        }
        else
        {
            return null;
        }
    }

    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
    {
        return SelectTemplateCore(item);
    }

}

我在做什么错?为什么内存从19mb增长到91mb?

[编辑]: 这里的完整解决方案:download

1 个答案:

答案 0 :(得分:2)

每次选择按钮时,DataTemplateSelector都会从“圆形”和“正方形”模板创建新的控件。通过将模板添加到ItemsControl的资源,并在InternalObjects-Collection上的每次更新中创建/处置控件,我能够避免这种情况:

    <ItemsControl ItemsSource="{Binding InternalObjects, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DataContext="{Binding SelectedButton}" Grid.Column="1">
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type local:Circles}">
                <TextBlock Text="This is the template for a circle too..." Foreground="Crimson" HorizontalAlignment="Center"></TextBlock>
            </DataTemplate>
            <DataTemplate DataType="{x:Type local:Squares}">
                <TextBlock Text="This is the template for a square too..." Foreground="Crimson" HorizontalAlignment="Center"></TextBlock>
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>

使用组合框对其进行测试:

    <ComboBox ItemsSource="{Binding ButtonsList}" Grid.Row="0" SelectedItem="{Binding SelectedButton, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <ComboBox.ItemTemplate>
            <DataTemplate DataType="x:String">
                <TextBlock Text="{Binding Name}" Foreground="Red" FontSize="15" Grid.Column="0" VerticalAlignment="Stretch" HorizontalAlignment="Center"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

根据模板的大小,它可能仍会消耗大量内存

要考虑的另一种选择是从模板中提取控件并创建它的单个实例(如果可能,例如ColorPicker)。

否则,您需要依靠C#/ UWP为您管理创建的控件。