Custom控件中的Datagrid未更新

时间:2015-06-17 18:42:32

标签: c# wpf xaml datagrid

在我的自定义控件中有一个DataGrid和两个按钮,一个用于在此DataGrid中添加行,另一个按钮用于删除元素。

(因为我的名声,我不能在这里发布图片,抱歉!): - (

我的自定义控制代码背后:

    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class CustonDatagrid : UserControl
    {
        public CustonDatagrid()
        {
            InitializeComponent();
        }

        #region DependencyProperty Content

        /// <summary>
        /// Registers a dependency property as backing store for the Content property
        /// </summary>
        public static readonly DependencyProperty ColectionProperty =
            DependencyProperty.Register("Colection",
            typeof(ObservableCollection<object>),
            typeof(CustonDatagrid),
            new FrameworkPropertyMetadata(null,
                  FrameworkPropertyMetadataOptions.AffectsRender |
                  FrameworkPropertyMetadataOptions.AffectsParentMeasure));

        /// <summary>
        /// Gets or sets the Content.
        /// </summary>
        /// <value>The Content.</value>
        public ObservableCollection<object> Colection
        {
            get { return (ObservableCollection<object>)GetValue(ColectionProperty); }
            set { SetValue(ColectionProperty, value); }
        }

        #endregion

        public static readonly RoutedEvent AddButtonEvent = EventManager.RegisterRoutedEvent(
            "AddButtonClick",
            RoutingStrategy.Bubble, 
            typeof (RoutedEventHandler),
            typeof (CustonDatagrid));

        public event RoutedEventHandler AddButtonClick
        {
            add { AddHandler(AddButtonEvent, value); }
            remove { RemoveHandler(AddButtonEvent, value);}
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var newEventArgs = new RoutedEventArgs(AddButtonEvent);
            RaiseEvent(newEventArgs);
        }
    }

我的.xaml:

    <UserControl x:Class="WpfCustomControlLibrary1.CustonDatagrid"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Name="CustonDataGrid">
    <Grid>
            <DockPanel LastChildFill="True" >
                <StackPanel DockPanel.Dock="Bottom" HorizontalAlignment="Right" Orientation="Horizontal">
                    <Button Margin="5" Width="20" Click="ButtonBase_OnClick" >+</Button>
                <Button Margin="5" Width="20">-</Button>
            </StackPanel>
                <DataGrid ItemsSource="{Binding ElementName=CustonDataGrid, Path=Colection}" DockPanel.Dock="Top"></DataGrid>
            </DockPanel>
    </Grid>
</UserControl>

在wpf windows中的用法:

xaml代码:

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfCustomControlLibrary1="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}, Path=Model}"
        >

    <Grid>
        <wpfCustomControlLibrary1:CustonDatagrid Colection="{Binding Path=Colection}" AddButtonClick="CustonDatagrid_OnAddButtonClick">

        </wpfCustomControlLibrary1:CustonDatagrid>
    </Grid>
</Window>

背后的代码+ View Model + datagrid行视图模型:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

    public MainWindow()
    {
        Model = new Model();
        InitializeComponent();
    }

    public Model Model { get; set; }

    private void CustonDatagrid_OnAddButtonClick(object sender, RoutedEventArgs e)
    {
        Model.AddElement();
    }
}

public class Model : INotifyPropertyChanged
{
    public ObservableCollection<DataGridRowModel> Colection { get; set; }

    public void AddElement()
    {
        if (Colection == null) Colection = new ObservableCollection<DataGridRowModel>();
        Colection.Add( new DataGridRowModel()
        {
            Name = "Test"
        });
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class DataGridRowModel
{
    public string Name { get; set; }
}

我遇到的问题是Datagrid没有显示添加到Collection的新元素。在调试时,我可以看到我的集合有很多元素(每次点击(+)按钮都有一个元素),但这些元素没有在视图中显示。

有人可以在我犯错误或(可能)丢失代码时给出提示吗?!?

感谢。

1 个答案:

答案 0 :(得分:0)

您在CustonDatagrid.xaml

中犯了一个小错误
<DataGrid ItemsSource="{Binding ElementName=CustonDataGrid, Path=Colection}" DockPanel.Dock="Top"></DataGrid>

没有名为 CustonDataGrid 的元素,因为元素从未被反映过。

将其更改为

<DataGrid ItemsSource="{Binding Path=Colection}"></DataGrid>

我还对您的MainWindow.cs

进行了细微更改
public partial class MainWindow : Window
{
    public MainWindow()
    {
        Model = new Model();
        InitializeComponent();
        this.DataContext = Model;
    }

    public Model Model { get; set; }

    private void CustonDatagrid_OnAddButtonClick(object sender, RoutedEventArgs e)
    {
        Model.AddElement();
    }
}

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfCustomControlLibrary1="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"
        Title="MainWindow" Height="350" Width="525">
    <ScrollViewer>
        <wpfCustomControlLibrary1:CustonDatagrid Colection="{Binding Colection,Mode=TwoWay}" AddButtonClick="CustonDatagrid_OnAddButtonClick">
        </wpfCustomControlLibrary1:CustonDatagrid>
    </ScrollViewer>
</Window>

Model.cs

添加了构造函数
public class Model : INotifyPropertyChanged
{
    public ObservableCollection<DataGridRowModel> Colection { get; set; }

    public Model()
    {
        Colection = new ObservableCollection<DataGridRowModel>();
    }
    public void AddElement()
    {
        Colection.Add(new DataGridRowModel { Name = "Test" });
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

我希望它也适用于你。