【问题标题】:How to get a WPF datagrid column resize event?如何获取 WPF 数据网格列调整大小事件?
【发布时间】:2013-10-28 06:14:23
【问题描述】:

我想从我的 ini 文件中动态加载和存储 Datagrid 列宽。每次调整列宽大小时写入我的 inifile。我可以为此使用哪个事件。任何机构都可以为此提供任何建议或示例代码。

【问题讨论】:

    标签: wpf c#-4.0 wpfdatagrid wpf-4.0


    【解决方案1】:

    我在此类事情的行为中使用应用程序设置并保存应用程序退出时的信息。

    用法

        <DataGrid>
            <i:Interaction.Behaviors>
                <local:DataGridBehavior GridSettings="{Binding Source={x:Static local:MySettings.Instance},Mode=OneWay}" />
            </i:Interaction.Behaviors>
        </DataGrid>
    

    设置

    [SettingsManageabilityAttribute(SettingsManageability.Roaming)]
    public sealed class MySettings: ApplicationSettingsBase, IGridSettings
    {
        private static readonly Lazy<MySettings> LazyInstance = new Lazy<MySettings>(() => new KadiaSettings());
    
        public static MySettingsInstance { get { return LazyInstance.Value; } }
    
        [UserScopedSettingAttribute()]
        [DefaultSettingValue("")]
        [SettingsSerializeAs(SettingsSerializeAs.Xml)]
        public SerializableDictionary<string, int> GridDisplayIndexList
        {
            get { return (SerializableDictionary<string, int>)this["GridDisplayIndexList"]; }
            set { this["GridDisplayIndexList"] = value; }
        }
    
        [UserScopedSettingAttribute()]
        [DefaultSettingValue("")]
        [SettingsSerializeAs(SettingsSerializeAs.Xml)]
        public SerializableDictionary<string, Visibility> GridColumnVisibilityList
        {
            get { return (SerializableDictionary<string, Visibility>)this["GridColumnVisibilityList"]; }
            set { this["GridColumnVisibilityList"] = value; }
        }
    
        [UserScopedSettingAttribute()]
        [DefaultSettingValue("")]
        [SettingsSerializeAs(SettingsSerializeAs.Xml)]
        public SerializableDictionary<string, double> GridColumnWidthList
        {
            get { return (SerializableDictionary<string, double>)this["GridColumnWidthList"]; }
            set { this["GridColumnWidthList"] = value; }
        }
    
        private MySettings()
        {
            Application.Current.Exit += OnExit;
        }
    
        private void OnExit(object sender, ExitEventArgs e)
        {
            this.Save();
        }
    }
    
    public interface IGridSettings: INotifyPropertyChanged
    {
        SerializableDictionary<string, int> GridDisplayIndexList { get; }
    
        SerializableDictionary<string, Visibility> GridColumnVisibilityList { get; }
    
        SerializableDictionary<string, double> GridColumnWidthList { get; }
    }
    
    [XmlRoot("Dictionary")]
    public class SerializableDictionary<TKey, TValue>: Dictionary<TKey, TValue>, IXmlSerializable 
    {
    
        #region IXmlSerializable Members
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }
    
        public void ReadXml(System.Xml.XmlReader reader)
        {
            var keySerializer = new XmlSerializer(typeof(TKey));
            var valueSerializer = new XmlSerializer(typeof(TValue));
    
            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();
    
            if (wasEmpty)
                return;
    
            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
            {
                reader.ReadStartElement("item");
    
                reader.ReadStartElement("key");
                var key = (TKey)keySerializer.Deserialize(reader);
                reader.ReadEndElement();
    
                reader.ReadStartElement("value");
                var value = (TValue)valueSerializer.Deserialize(reader);
                reader.ReadEndElement();
    
                this.Add(key, value);
    
                reader.ReadEndElement();
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }
    
        public void WriteXml(System.Xml.XmlWriter writer)
        {
            var keySerializer = new XmlSerializer(typeof(TKey));
            var valueSerializer = new XmlSerializer(typeof(TValue));
    
            foreach (TKey key in this.Keys)
            {
                writer.WriteStartElement("item");
    
                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();
    
                writer.WriteStartElement("value");
                TValue value = this[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();
    
                writer.WriteEndElement();
            }
        }
        #endregion
    }
    

    行为

    public class DataGridBehavior : Behavior<DataGrid>
    {
    
        public static readonly DependencyProperty GridSettingsProperty =
            DependencyProperty.Register("GridSettings", typeof(IGridSettings), typeof(DataGridBehavior), null);
    
    
        public IGridSettings GridSettings
        {
            get { return (IGridSettings)GetValue(GridSettingsProperty); }
            set { SetValue(GridSettingsProperty, value); }
        }
    
        public DataGridICollectionViewSortMerkerBehavior()
        {
            Application.Current.Exit += CurrentExit;
        }
    
        private void CurrentExit(object sender, ExitEventArgs e)
        {
            SetSettings();
        }
    
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += AssociatedObjectLoaded;
            AssociatedObject.Unloaded += AssociatedObjectUnloaded;
        }
    
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.Loaded -= AssociatedObjectLoaded;
            AssociatedObject.Unloaded -= AssociatedObjectUnloaded;
        }
    
        private void AssociatedObjectUnloaded(object sender, RoutedEventArgs e)
        {
            SetSettings();
        }
    
        void AssociatedObjectLoaded(object sender, RoutedEventArgs e)
        {
            var settings = GridSettings;
    
            var columns = AssociatedObject.Columns.ToList();
            var colCount = columns.Count;
            foreach (var column in columns)
            {
                var key = column.Header.ToString();
    
                if (settings.GridDisplayIndexList.ContainsKey(key))
                {
                    //manchmal wird -1 als index abgespeichert
                    var index = settings.GridDisplayIndexList[key];
                    if(index > 0 && index < colCount)
                        column.DisplayIndex = index;
                }
    
                if (settings.GridColumnVisibilityList.ContainsKey(key))
                {
                    column.Visibility = settings.GridColumnVisibilityList[key];
                }
    
                if (settings.GridColumnWidthList.ContainsKey(key))
                {
                    column.Width = new DataGridLength(settings.GridColumnWidthList[key]);
                }
            }           
        }
    
    
        private void SetSettings()
        {
            var settings = GridSettings;
    
            foreach (var column in AssociatedObject.Columns)
            {
                var key = column.Header.ToString();
                var displayindex = column.DisplayIndex;
                var visibility = column.Visibility;
                var width = column.ActualWidth;
    
                if (settings.GridDisplayIndexList.ContainsKey(key))
                {
                    settings.GridDisplayIndexList[key] = displayindex;
                }
                else
                {
                    settings.GridDisplayIndexList.Add(key, displayindex);
                }
    
                if (settings.GridColumnVisibilityList.ContainsKey(key))
                {
                    settings.GridColumnVisibilityList[key] = visibility;
                }
                else
                {
                    settings.GridColumnVisibilityList.Add(key, visibility);
                }
    
                if (settings.GridColumnWidthList.ContainsKey(key))
                {
                    settings.GridColumnWidthList[key] = width;
                }
                else
                {
                    settings.GridColumnWidthList.Add(key, width);
                }
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-24
      • 1970-01-01
      • 2017-02-26
      • 2012-07-03
      • 2011-04-30
      • 2012-09-16
      • 2011-08-21
      • 2011-01-07
      • 2017-08-04
      相关资源
      最近更新 更多