Problem when extending asp:Repeater with DataPager - c#

I'm extending asp:Repeater to use DataPager, and now my code work with SqlDataSource. To get better performance, I want to use ObjectDataSource with it, but I have to use QueryStringField of DataPager, otherwise I have to click page number twice to make it work. Can any one help on this? this is my code:
namespace WebTest.UserControl
{
public class PageableRepeater : Repeater, IPageableItemContainer
{
private static readonly object EventTotalRowCountAvailable = new object();
private int _startRowIndex = 0;
private int _maximumRows = -1;
private int _totalRowCount = -1;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}
protected override void LoadControlState(object savedState)
{
_startRowIndex = 0;
_maximumRows = -1;
_totalRowCount = -1;
object[] state = savedState as object[];
if (state != null)
{
base.LoadControlState(state[0]);
if (state[1] != null)
{
_totalRowCount = (int)state[1];
}
}
else
{
base.LoadControlState(null);
}
if (!IsViewStateEnabled)
{
OnTotalRowCountAvailable(new PageEventArgs(_startRowIndex, _maximumRows, _totalRowCount));
}
}
protected override object SaveControlState()
{
object baseState = base.SaveControlState();
if (baseState != null || _totalRowCount != -1)
{
object[] state = new object[2];
state[0] = baseState;
state[1] = _totalRowCount;
return state;
}
return true;
}
protected override System.Collections.IEnumerable GetData()
{
ListViewPagedDataSource pagedDataSource = new ListViewPagedDataSource();
pagedDataSource.StartRowIndex = _startRowIndex;
pagedDataSource.MaximumRows = _maximumRows;
if (DataSource is ObjectDataSource)
{
SelectArguments.StartRowIndex = _startRowIndex;
SelectArguments.MaximumRows = _maximumRows;
SelectArguments.RetrieveTotalRowCount = true;
pagedDataSource.DataSource = base.GetData();
_totalRowCount = SelectArguments.TotalRowCount;
pagedDataSource.AllowServerPaging = true;
pagedDataSource.TotalRowCount = _totalRowCount;
}
else
{
pagedDataSource.DataSource = base.GetData();
pagedDataSource.AllowServerPaging = false;
pagedDataSource.TotalRowCount = 0;
_totalRowCount = pagedDataSource.DataSourceCount;
}
return pagedDataSource;
}
protected override void CreateControlHierarchy(bool useDataSource)
{
base.CreateControlHierarchy(useDataSource);
OnTotalRowCountAvailable(new PageEventArgs(_startRowIndex, _maximumRows, _totalRowCount));
}
private void OnTotalRowCountAvailable(PageEventArgs pageEventArgs)
{
EventHandler<PageEventArgs> handler = (EventHandler<PageEventArgs>)Events[EventTotalRowCountAvailable];
if (handler != null)
{
handler(this, pageEventArgs);
}
}
public int MaximumRows
{
get { return _maximumRows; }
}
public int StartRowIndex
{
get { return _startRowIndex; }
}
public void SetPageProperties(int startRowIndex, int maximumRows, bool databind)
{
if (maximumRows < 1)
{
throw new ArgumentOutOfRangeException("maximumRows");
}
if (startRowIndex < 0)
{
throw new ArgumentOutOfRangeException("startRowIndex");
}
_startRowIndex = startRowIndex;
_maximumRows = maximumRows;
if (databind)
{
RequiresDataBinding = true;
}
}
public event EventHandler<PageEventArgs> TotalRowCountAvailable
{
add
{
Events.AddHandler(EventTotalRowCountAvailable, value);
}
remove
{
Events.RemoveHandler(EventTotalRowCountAvailable, value);
}
}
}
}
By the way, I found another implementation to this on CodeProject, but I don't think it use IPageableItemContainer very well.

I know this is an old one, but I've recently been looking for a solution to using the Repeater with a DataPager control.
Most research takes me to this CodeProject article, but it seems like a bit of a hack to me. I've worked on this problem a bit, and put it to the side for a while as I was spinning my wheels on it, until I saw your question and sample code. I was able to take your code and apply it to mine to get a working solution (at least it works for me). With the DataPagerRepeater control below, I'm able to drop the DataPagerRepeater, DataPager, and a DataSource (ObjectDataSource, etc) on the page. Set the DataPagerRepeaters DataSource or DataSourceID to point to the data source, then set the DataPagers PagedControlID to the DataPagerRepeater. Seems to work great.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace My.Web.UI.WebControls
{
/// <summary>
/// Extends the Repeater to be compatable with a DataPager
/// </summary>
/// <remarks>
/// To page through data in a control that implements the IPageableItemContainer interface, DataPager control can be used.
/// Repeater does not support paging and does not implement IPageableItemContainer interface. ListView is the only control that works with DataPager.
///
/// The DataPager control supports built-in paging user interface (UI). NumericPagerField object enables users to select a page of data by page number.
/// NextPreviousPagerField object enables users to move through pages of data one page at a time, or to jump to the first or last page of data.
/// The size of the pages of data is set by using the PageSize property of the DataPager control. One or more pager field objects can be used in
/// a single DataPager control. Custom paging UI can be created by using the TemplatePagerField object. In the TemplatePagerField template,
/// the DataPager control is referenced by using the Container property which provides access to the properties of the DataPager control.
/// These properties include the starting row index, the page size, and the total number of rows currently bound to the control.
/// </remarks>
[ToolboxData("<my:DataPagerRepeater runat=server></my:DataPagerRepeater>")]
[Themeable(true)]
public class DataPagerRepeater : Repeater, IPageableItemContainer
{
/// <summary>Gets the maximum number of items to display on a single page of the <see cref="T:InteriorHealth.Web.UI.WebControls.DataPagerRepeater" /> control.
/// </summary>
/// <returns>The maximum number of items to display on a single page of the <see cref="T:InteriorHealth.Web.UI.WebControls.DataPagerRepeater" /> control.
/// </returns>
public int MaximumRows
{
get;
//{
// return ViewState["maxrows"] != null ? (int)ViewState["maxrows"] : -1;
//}
private set;
//{
// ViewState["maxrows"] = value;
//}
}
/// <summary>Gets the index of the first record that is displayed on a page of data in the <see cref="T:InteriorHealth.Web.UI.WebControls.DataPagerRepeater" /> control.
/// </summary>
/// <returns>The index of the first record that is displayed on a page of data in the <see cref="T:InteriorHealth.Web.UI.WebControls.DataPagerRepeater" /> control.
/// </returns>
public int StartRowIndex
{
get;
//{
// return ViewState["startrowindex"] != null ? (int)ViewState["startrowindex"] : -1;
//}
private set;
//{
// ViewState["startrowindex"] = value;
//}
}
/// <summary>
/// Total number of rows that are avialable, regardless of what is currently being displayed
/// </summary>
private int TotalRowsAvailable
{
get;
//{
// return ViewState["totalrows"] != null ? (int)ViewState["totalrows"] : -1;
//}
set;
//{
// ViewState["totalrows"] = value;
//}
}
private static readonly object EventPagePropertiesChanged = new object();
/// <summary>Occurs when the page properties change, after the <see cref="T:InteriorHealth.Web.UI.WebControls.DataPagerRepeater" /> control sets the new values.
/// </summary>
public event EventHandler PagePropertiesChanged
{
add
{
base.Events.AddHandler(DataPagerRepeater.EventPagePropertiesChanged, value);
}
remove
{
base.Events.RemoveHandler(DataPagerRepeater.EventPagePropertiesChanged, value);
}
}
private static readonly object EventPagePropertiesChanging = new object();
/// <summary>Occurs when the page properties change, but before the <see cref="T:InteriorHealth.Web.UI.WebControls.DataPagerRepeater" /> control sets the new values.
/// </summary>
public event EventHandler<PagePropertiesChangingEventArgs> PagePropertiesChanging
{
add
{
base.Events.AddHandler(DataPagerRepeater.EventPagePropertiesChanging, value);
}
remove
{
base.Events.RemoveHandler(DataPagerRepeater.EventPagePropertiesChanging, value);
}
}
private static readonly object EventTotalRowCountAvailable = new object();
/// <summary>For a description of this member, see <see cref="E:System.Web.UI.WebControls.IPageableItemContainer.TotalRowCountAvailable" />.
/// </summary>
public event EventHandler<PageEventArgs> TotalRowCountAvailable
{
add
{
base.Events.AddHandler(DataPagerRepeater.EventTotalRowCountAvailable, value);
}
remove
{
base.Events.RemoveHandler(DataPagerRepeater.EventTotalRowCountAvailable, value);
}
}
/// <summary>
/// Register the control as one who's control state needs to be persisted
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}
/// <summary>
/// Initialize the start row index, maximum rows, and total rows available values. Load the total rows available from viewstate.
/// </summary>
/// <param name="savedState"></param>
protected override void LoadControlState(object savedState)
{
this.StartRowIndex = 0;
this.MaximumRows = -1;
this.TotalRowsAvailable = -1;
object[] state = savedState as object[];
if (state != null)
{
base.LoadControlState(state[0]);
if (state[1] != null)
{
this.TotalRowsAvailable = (int)state[1];
}
}
else
{
base.LoadControlState(null);
}
if (!IsViewStateEnabled)
{
OnTotalRowCountAvailable(new PageEventArgs(this.StartRowIndex, this.MaximumRows, this.TotalRowsAvailable));
}
}
/// <summary>
/// Save the total rows available value to viewstate
/// </summary>
/// <returns></returns>
protected override object SaveControlState()
{
object baseState = base.SaveControlState();
if (baseState != null || this.TotalRowsAvailable != -1)
{
object[] state = new object[2];
state[0] = baseState;
state[1] = this.TotalRowsAvailable;
return state;
}
return true;
}
/// <summary>Sets the properties of a page of data in the <see cref="T:InteriorHealth.Web.UI.WebControls.DataPagerRepeater" /> control.
/// </summary>
/// <param name="startRowIndex">The index of the first record on the page.</param>
/// <param name="maximumRows">The maximum number of items on a single page.</param>
/// <param name="databind">true to rebind the control after the properties are set; otherwise, false.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="maximumRows" /> is less than 1.-or-<paramref name="startRowIndex" /> is less than 0.
/// </exception>
public void SetPageProperties(int startRowIndex, int maximumRows, bool databind)
{
if (maximumRows < 1)
{
throw new ArgumentOutOfRangeException("maximumRows");
}
if (startRowIndex < 0)
{
throw new ArgumentOutOfRangeException("startRowIndex");
}
if (this.StartRowIndex != startRowIndex || this.StartRowIndex != maximumRows)
{
PagePropertiesChangingEventArgs pagePropertiesChangingEventArgs = new PagePropertiesChangingEventArgs(startRowIndex, maximumRows);
if (databind)
{
this.OnPagePropertiesChanging(pagePropertiesChangingEventArgs);
}
this.StartRowIndex = pagePropertiesChangingEventArgs.StartRowIndex;
this.MaximumRows = pagePropertiesChangingEventArgs.MaximumRows;
if (databind)
{
this.OnPagePropertiesChanged(EventArgs.Empty);
}
}
if (databind)
{
this.RequiresDataBinding = true;
}
//this.OnTotalRowCountAvailable(new PageEventArgs(this.StartRowIndex, this.MaximumRows, this.TotalRowsAvailable));
}
/// <summary>
/// Creates a control hierarchy, with or without the specified data source.
/// </summary>
/// <param name="useDataSource">
/// Indicates whether to use the specified data source.
/// </param>
protected override void CreateControlHierarchy(bool useDataSource)
{
base.CreateControlHierarchy(useDataSource);
OnTotalRowCountAvailable(new PageEventArgs(this.StartRowIndex, this.MaximumRows, this.TotalRowsAvailable));
}
/// <summary>Returns an <see cref="T:System.Collections.IEnumerable" /> interface from the data source.</summary>
/// <returns>An object implementing <see cref="T:System.Collections.IEnumerable" /> that represents the data from the data source.</returns>
protected override System.Collections.IEnumerable GetData()
{
System.Collections.IEnumerable data = base.GetData();
this.TotalRowsAvailable = this.SelectArguments.TotalRowCount;
this.OnTotalRowCountAvailable(new PageEventArgs(this.StartRowIndex, this.MaximumRows, this.TotalRowsAvailable));
return data;
}
/// <summary>Raises the <see cref="E:InteriorHealth.Web.UI.WebControls.DataPagerRepeater.PagePropertiesChanging" /> event.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnPagePropertiesChanging(PagePropertiesChangingEventArgs e)
{
EventHandler<PagePropertiesChangingEventArgs> eventHandler = (EventHandler<PagePropertiesChangingEventArgs>)base.Events[DataPagerRepeater.EventPagePropertiesChanging];
if (eventHandler != null)
{
eventHandler(this, e);
}
}
/// <summary>Raises the <see cref="E:InteriorHealth.Web.UI.WebControls.DataPagerRepeater.SelectedIndexChanged" /> event.</summary>
/// <param name="e">The event data.</param>
protected virtual void OnPagePropertiesChanged(EventArgs e)
{
EventHandler eventHandler = (EventHandler)base.Events[DataPagerRepeater.EventPagePropertiesChanged];
if (eventHandler != null)
{
eventHandler(this, e);
}
}
/// <summary>Raises the <see cref="E:InteriorHealth.Web.UI.WebControls.DataPagerRepeater.PagePropertiesChanging" /> event.</summary>
/// <param name="e">The event data.</param>
protected virtual void OnTotalRowCountAvailable(PageEventArgs e)
{
EventHandler<PageEventArgs> eventHandler = (EventHandler<PageEventArgs>)base.Events[DataPagerRepeater.EventTotalRowCountAvailable];
if (eventHandler != null)
{
eventHandler(this, e);
}
}
/// <summary>
/// Override the selection of rows that we need
/// </summary>
/// <returns></returns>
protected override DataSourceSelectArguments CreateDataSourceSelectArguments()
{
DataSourceSelectArguments arg = base.CreateDataSourceSelectArguments();
arg.StartRowIndex = this.StartRowIndex;
arg.MaximumRows = this.MaximumRows;
return arg;
}
}
}

Related

Can put xml reader function into D3drenderer.cs?

Below is the standard d3drenderer.cs file coding:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using System.Xml.Linq;
namespace WPFMediaKit.DirectShow.Controls
{
/// <summary>
/// The D3DRenderer class provides basic functionality needed
/// to render a D3D surface. This class is abstract.
/// </summary>
public abstract class D3DRenderer : FrameworkElement
{
private string workingDirectory = AppDomain.CurrentDomain.BaseDirectory;
/// <summary>
/// The D3DImage used to render video
/// </summary>
private D3DImage m_d3dImage;
/// <summary>
/// The Image control that has the source
/// to the D3DImage
/// </summary>
private Image m_videoImage;
/// <summary>
/// We keep reference to the D3D surface so
/// we can delay loading it to avoid a black flicker
/// when loading new media
/// </summary>
private IntPtr m_pBackBuffer = IntPtr.Zero;
/// <summary>
/// Flag to tell us if we have a new D3D
/// Surface available
/// </summary>
private bool m_newSurfaceAvailable;
/// <summary>
/// A weak reference of D3DRenderers that have been cloned
/// </summary>
private readonly List<WeakReference> m_clonedD3Drenderers = new List<WeakReference>();
/// <summary>
/// Backing field for the RenderOnCompositionTargetRendering flag.
/// </summary>
private bool m_renderOnCompositionTargetRendering;
/// <summary>
/// Temporary storage for the RenderOnCompositionTargetRendering flag.
/// This is used to remember the value for when the control is loaded and unloaded.
/// </summary>
private bool m_renderOnCompositionTargetRenderingTemp;
#region Stretch
public static readonly DependencyProperty StretchProperty =
DependencyProperty.Register("Stretch", typeof(Stretch), typeof(D3DRenderer),
new FrameworkPropertyMetadata(Stretch.Uniform,
new PropertyChangedCallback(OnStretchChanged)));
/// <summary>
/// Defines what rules are applied to the stretching of the video
/// </summary>
public Stretch Stretch
{
get { return (Stretch)GetValue(StretchProperty); }
set { SetValue(StretchProperty, value); }
}
private static void OnStretchChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((D3DRenderer)d).OnStretchChanged(e);
}
private void OnStretchChanged(DependencyPropertyChangedEventArgs e)
{
m_videoImage.Stretch = (Stretch) e.NewValue;
}
#endregion
#region IsRenderingEnabled
public static readonly DependencyProperty IsRenderingEnabledProperty =
DependencyProperty.Register("IsRenderingEnabled", typeof(bool), typeof(D3DRenderer),
new FrameworkPropertyMetadata(true));
/// <summary>
/// Enables or disables rendering of the video
/// </summary>
public bool IsRenderingEnabled
{
get { return (bool)GetValue(IsRenderingEnabledProperty); }
set { SetValue(IsRenderingEnabledProperty, value); }
}
#endregion
#region NaturalVideoHeight
private static readonly DependencyPropertyKey NaturalVideoHeightPropertyKey
= DependencyProperty.RegisterReadOnly("NaturalVideoHeight", typeof(int), typeof(MediaElementBase),
new FrameworkPropertyMetadata(0));
public static readonly DependencyProperty NaturalVideoHeightProperty
= NaturalVideoHeightPropertyKey.DependencyProperty;
/// <summary>
/// Gets the natural pixel height of the current media.
/// The value will be 0 if there is no video in the media.
/// </summary>
public int NaturalVideoHeight
{
get { return (int)GetValue(NaturalVideoHeightProperty); }
}
/// <summary>
/// Internal method to set the read-only NaturalVideoHeight DP
/// </summary>
protected void SetNaturalVideoHeight(int value)
{
SetValue(NaturalVideoHeightPropertyKey, value);
}
#endregion
#region NaturalVideoWidth
private static readonly DependencyPropertyKey NaturalVideoWidthPropertyKey
= DependencyProperty.RegisterReadOnly("NaturalVideoWidth", typeof(int), typeof(MediaElementBase),
new FrameworkPropertyMetadata(0));
public static readonly DependencyProperty NaturalVideoWidthProperty
= NaturalVideoWidthPropertyKey.DependencyProperty;
/// <summary>
/// Gets the natural pixel width of the current media.
/// The value will be 0 if there is no video in the media.
/// </summary>
public int NaturalVideoWidth
{
get { return (int)GetValue(NaturalVideoWidthProperty); }
}
/// <summary>
/// Internal method to set the read-only NaturalVideoWidth DP
/// </summary>
protected void SetNaturalVideoWidth(int value)
{
SetValue(NaturalVideoWidthPropertyKey, value);
}
#endregion
#region HasVideo
private static readonly DependencyPropertyKey HasVideoPropertyKey
= DependencyProperty.RegisterReadOnly("HasVideo", typeof(bool), typeof(MediaElementBase),
new FrameworkPropertyMetadata(false));
public static readonly DependencyProperty HasVideoProperty
= HasVideoPropertyKey.DependencyProperty;
/// <summary>
/// Is true if the media contains renderable video
/// </summary>
public bool HasVideo
{
get { return (bool)GetValue(HasVideoProperty); }
}
/// <summary>
/// Internal method for setting the read-only HasVideo DP
/// </summary>
protected void SetHasVideo(bool value)
{
SetValue(HasVideoPropertyKey, value);
}
#endregion
protected D3DRenderer()
{
InitializeD3DVideo();
/* Hook into the framework events */
Loaded += D3DRenderer_Loaded;
Unloaded += D3DRenderer_Unloaded;
}
/// <summary>
/// Handler for when the D3DRenderer is unloaded
/// </summary>
private void D3DRenderer_Unloaded(object sender, RoutedEventArgs e)
{
/* Remember what the property value was */
m_renderOnCompositionTargetRenderingTemp = RenderOnCompositionTargetRendering;
/* Make sure to unhook the static event hook because we are unloading */
RenderOnCompositionTargetRendering = false;
}
/// <summary>
/// Handler for when the D3DRenderer is loaded
/// </summary>
private void D3DRenderer_Loaded(object sender, RoutedEventArgs e)
{
/* Restore the property's value */
RenderOnCompositionTargetRendering = m_renderOnCompositionTargetRenderingTemp;
}
/// <summary>
/// Initializes the D3DRenderer control
/// </summary>
protected virtual void InitializeD3DVideo()
{
if (m_videoImage != null)
return;
/* Create our Image and it's D3DImage source */
m_videoImage = new Image();
m_d3dImage = new D3DImage();
/* We hook into this event to handle when a D3D device is lost */
D3DImage.IsFrontBufferAvailableChanged += D3DImage_IsFrontBufferAvailableChanged;
/* Set our default stretch value of our video */
m_videoImage.Stretch = (Stretch)StretchProperty.DefaultMetadata.DefaultValue;
var activeProfiles = XElement.Load(workingDirectory + "ProfilesDisplay.xml");
var a = activeProfiles.Element("_nABC").Value;
/* Our source of the video image is the D3DImage */
m_videoImage.Source = D3DImage;
/* Register the Image as a visual child */
AddVisualChild(m_videoImage);
}
/// <summary>
/// This should only fire when a D3D device is lost
/// </summary>
private void D3DImage_IsFrontBufferAvailableChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (!D3DImage.IsFrontBufferAvailable)
return;
/* Flag that we have a new surface, even
* though we really don't */
m_newSurfaceAvailable = true;
/* Force feed the D3DImage the Surface pointer */
SetBackBufferInternal(m_pBackBuffer);
}
protected override Size MeasureOverride(Size availableSize)
{
m_videoImage.Measure(availableSize);
return m_videoImage.DesiredSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
m_videoImage.Arrange(new Rect(finalSize));
return finalSize;
}
protected override int VisualChildrenCount
{
get
{
return 1;
}
}
protected override Visual GetVisualChild(int index)
{
if (index > 0)
throw new IndexOutOfRangeException();
return m_videoImage;
}
protected D3DImage D3DImage
{
get
{
return m_d3dImage;
}
}
protected Image VideoImage
{
get
{
return m_videoImage;
}
}
/// <summary>
/// Renders the video with WPF's rendering using the CompositionTarget.Rendering event
/// </summary>
protected bool RenderOnCompositionTargetRendering
{
get
{
return m_renderOnCompositionTargetRendering;
}
set
{
/* If it is being set to true and it was previously false
* then hook into the event */
if (value && !m_renderOnCompositionTargetRendering)
CompositionTarget.Rendering += CompositionTarget_Rendering;
else if(!value)
CompositionTarget.Rendering -= CompositionTarget_Rendering;
m_renderOnCompositionTargetRendering = value;
m_renderOnCompositionTargetRenderingTemp = value;
}
}
private void CompositionTarget_Rendering(object sender, EventArgs e)
{
InternalInvalidateVideoImage();
}
/// <summary>
/// Used as a clone for a D3DRenderer
/// </summary>
private class ClonedD3DRenderer : D3DRenderer
{}
/// <summary>
/// Creates a clone of the D3DRenderer. This is a work for the visual
/// brush not working cross-threaded
/// </summary>
/// <returns></returns>
public D3DRenderer CloneD3DRenderer()
{
var renderer = new ClonedD3DRenderer();
lock(m_clonedD3Drenderers)
{
m_clonedD3Drenderers.Add(new WeakReference(renderer));
}
renderer.SetBackBuffer(m_pBackBuffer);
return renderer;
}
/// <summary>
/// Cleans up any dead references we may have to any cloned renderers
/// </summary>
private void CleanZombieRenderers()
{
lock(m_clonedD3Drenderers)
{
var deadObjects = new List<WeakReference>();
for (int i = 0; i < m_clonedD3Drenderers.Count; i++)
{
if (!m_clonedD3Drenderers[i].IsAlive)
deadObjects.Add(m_clonedD3Drenderers[i]);
}
foreach(var deadGuy in deadObjects)
{
m_clonedD3Drenderers.Remove(deadGuy);
}
}
}
/// <summary>
/// Configures D3DImage with a new surface. The back buffer is
/// not set until we actually receive a frame, this way we
/// can avoid a black flicker between media changes
/// </summary>
/// <param name="backBuffer">The unmanaged pointer to the Direct3D Surface</param>
protected void SetBackBuffer(IntPtr backBuffer)
{
/* We only do this if target rendering is enabled because we must use an Invoke
* instead of a BeginInvoke to keep the Surfaces in sync and Invoke could be dangerous
* in other situations */
if(RenderOnCompositionTargetRendering)
{
if (!D3DImage.Dispatcher.CheckAccess())
{
D3DImage.Dispatcher.Invoke((Action)(() => SetBackBuffer(backBuffer)), DispatcherPriority.Render);
return;
}
}
/* Flag a new surface */
m_newSurfaceAvailable = true;
m_pBackBuffer = backBuffer;
/* Make a special case for target rendering */
if (RenderOnCompositionTargetRendering)
{
SetBackBufferInternal(m_pBackBuffer);
}
SetBackBufferForClones();
}
/// <summary>
/// Sets the backbuffer for any cloned D3DRenderers
/// </summary>
private void SetBackBufferForClones()
{
lock (m_clonedD3Drenderers)
{
CleanZombieRenderers();
foreach (var rendererRef in m_clonedD3Drenderers)
{
var renderer = rendererRef.Target as D3DRenderer;
if (renderer != null)
renderer.SetBackBuffer(m_pBackBuffer);
}
}
}
/// <summary>
/// Configures D3DImage with a new surface. This happens immediately
/// </summary>
private void SetBackBufferInternal(IntPtr backBuffer)
{
/* Do nothing if we don't have a new surface available */
if (!m_newSurfaceAvailable)
return;
if(!D3DImage.Dispatcher.CheckAccess())
{
D3DImage.Dispatcher.BeginInvoke((Action)(() => SetBackBufferInternal(backBuffer)));
return;
}
/* We have this around a try/catch just in case we
* lose the device and our Surface is invalid. The
* try/catch may not be needed, but testing needs
* to take place before it's removed */
try
{
D3DImage.Lock();
D3DImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, backBuffer);
D3DImage.Unlock();
SetNaturalWidthHeight();
}
catch (Exception)
{ }
/* Clear our flag, so this won't be ran again
* until a new surface is sent */
m_newSurfaceAvailable = false;
}
private void SetNaturalWidthHeight()
{
SetNaturalVideoHeight(m_d3dImage.PixelHeight);
SetNaturalVideoWidth(m_d3dImage.PixelWidth);
}
protected void InvalidateVideoImage()
{
if (!m_renderOnCompositionTargetRendering)
InternalInvalidateVideoImage();
}
/// <summary>
/// Invalidates the entire Direct3D image, notifying WPF to redraw
/// </summary>
protected void InternalInvalidateVideoImage()
{
/* Ensure we run on the correct Dispatcher */
if(!D3DImage.Dispatcher.CheckAccess())
{
D3DImage.Dispatcher.BeginInvoke((Action)(() => InvalidateVideoImage()));
return;
}
/* If there is a new Surface to set,
* this method will do the trick */
SetBackBufferInternal(m_pBackBuffer);
/* Only render the video image if possible, or if IsRenderingEnabled is true */
if (D3DImage.IsFrontBufferAvailable && IsRenderingEnabled && m_pBackBuffer != IntPtr.Zero)
{
try
{
/* Invalidate the entire image */
D3DImage.Lock();
D3DImage.AddDirtyRect(new Int32Rect(0, /* Left */
0, /* Top */
D3DImage.PixelWidth, /* Width */
D3DImage.PixelHeight /* Height */));
D3DImage.Unlock();
}
catch
{ }
}
/* Invalidate all of our cloned D3DRenderers */
InvalidateClonedVideoImages();
}
/// <summary>
/// Invalidates any possible cloned renderer we may have
/// </summary>
private void InvalidateClonedVideoImages()
{
lock(m_clonedD3Drenderers)
{
CleanZombieRenderers();
foreach(var rendererRef in m_clonedD3Drenderers)
{
var renderer = rendererRef.Target as D3DRenderer;
if(renderer != null)
renderer.InvalidateVideoImage();
}
}
}
}
}
In the InitializeD3DVideo() function, I try to read a xml file from a location from the harddisk. But it can't be done.
Is it that the d3drenderer.cs cannot read from a xml file? I just want to read a value from _nABC of the xml file.
This has nothing to do with the D3DRenderer.
The path to the XML file is wrong. There is a '/' (or '\') missing between the workingDirectory and the + "ProfilesDisplay.xml".
If you don't know your path strings, the best method to combine these is System.IO.Path.Combine.

How can this NullReferenceException happen?

I'm investigation the following NRE:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Collections.Generic.GenericEqualityComparer`1.GetHashCode(T obj)
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.ContainsKey(TKey key)
at UC4.Decision.Core.Event.EventObjectHeader.get_Item(String key)
...
My EventObjectHeader class looks like this:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using UC4.Common.Utils.Xml;
namespace UC4.Decision.Core.Event
{
/// <summary>
/// Enumeration of the event priority.
/// </summary>
public enum EventPriority
{
/// <summary>
/// Event Priority Low
/// </summary>
Low = 0,
/// <summary>
/// Event Priority Medium (Default)
/// </summary>
Medium = 1,
/// <summary>
/// Event Priority High
/// </summary>
High = 2,
}
/// <summary>
/// Structure for the header information of an event object.
/// </summary>
/// <seealso cref="EventObject"/>
[Serializable]
public class EventObjectHeader : IEventObjectHeader, ISerializable
{
public const string KEY_TYPEURI = "typeUri";
/// <summary>
/// Fixed key which is used to store the predefined header element GUID.
/// </summary>
public const string KEY_GUID = "guid";
/// <summary>
/// Fixed key which is used to store the predefined header element IsPersistent.
/// </summary>
public const string KEY_ISPERSISTENT = "isPersistent";
/// <summary>
/// Fixed key which is used to store the time created in eventbase timezone of the Event.
/// </summary>
public const string KEY_TIME_CREATED = "timeCreated";
/// <summary>
/// Fixed key which is used to store the time created in UTC timezone of the Event.
/// </summary>
public const string KEY_TIME_CREATED_UTC = "timeCreatedUTC";
/// <summary>
/// Fixed key which is used to store the predefined header element Priority.
/// </summary>
public const string KEY_PRIORITY = "priority";
// internal data structure to store header elements as string tuples
private readonly IDictionary<string, string> _internal = new Dictionary<string, string>(6);
// lock for read and write requests to the internal dictionary
private readonly ReaderWriterLockSlim _internalDictionaryLock = new ReaderWriterLockSlim();
// caching dictionary
protected readonly Hashtable _cachedHeaderAttributes = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// default header attributes (always loaded because they are columns of EB_EVENTS)
/// </summary>
public static readonly ICollection<String> DEFAULT_ATTRIBUTES = new List<string>(new[]
{
KEY_GUID, KEY_TIME_CREATED,
KEY_TIME_CREATED_UTC,KEY_TYPEURI
});
/// <summary>
/// Initializes a new instance of the <see cref="EventObjectHeader"/> class.
/// </summary>
public EventObjectHeader()
{
}
/// <summary>
/// Indicates whether the event is persistent
/// </summary>
public bool IsPersistent
{
get
{
if (ContainsKey(KEY_ISPERSISTENT) == false)
{
return false;
}
return GetValueAs<bool>(KEY_ISPERSISTENT);
}
set { SetValue(KEY_ISPERSISTENT, value); }
}
/// <summary>
/// Initializes a new instance of the <see cref="EventObjectHeader"/> class.
/// </summary>
/// <param name="eventObjectHeaderToCopy">The event object header to copy.</param>
private EventObjectHeader(IEventObjectHeader eventObjectHeaderToCopy) : this()
{
List<String> keys = new List<string>(eventObjectHeaderToCopy.Keys);
foreach (string key in keys)
{
Add(key, eventObjectHeaderToCopy[key]);
}
}
/// <summary>
/// Property for accessing the predefined header element GUID.
/// </summary>
public virtual Guid Guid
{
get
{
if (ContainsKey(KEY_GUID) == false)
{
return Guid.Empty;
}
return GetValueAs<Guid>(KEY_GUID);
}
set { SetValue(KEY_GUID, value); }
}
/// <summary>
/// Property for accessing the predefined header element LocalTimeCreated.
/// </summary>
public virtual DateTime TimeCreated
{
get
{
if (ContainsKey(KEY_TIME_CREATED) == false)
{
return default(DateTime);
}
return GetValueAs<DateTime>(KEY_TIME_CREATED);
}
set { SetValue(KEY_TIME_CREATED, value); }
}
/// <summary>
/// Property for accessing the predefined header element UTC Time created
/// </summary>
public virtual DateTime TimeCreatedUTC
{
get
{
if (ContainsKey(KEY_TIME_CREATED_UTC) == false)
{
return default(DateTime);
}
return GetValueAs<DateTime>(KEY_TIME_CREATED_UTC);
}
set { SetValue(KEY_TIME_CREATED_UTC, value); }
}
/// <summary>
/// Property for accessing the predefined header element Priority.
/// </summary>
public virtual EventPriority Priority
{
get
{
if (ContainsKey(KEY_PRIORITY) == false)
{
return EventObjectHeaderHelper.DEFAULT_PRIORITY;
}
return GetValueAs<EventPriority>(KEY_PRIORITY);
}
set { SetValue(KEY_PRIORITY, value); }
}
/// <summary>
/// Make a copy of the event object header instance.
/// </summary>
/// <returns>New instance with the same values</returns>
public virtual EventObjectHeader Copy()
{
return new EventObjectHeader(this);
}
/// <summary>
/// Clear the event object header.
/// </summary>
public virtual void Clear()
{
_internalDictionaryLock.EnterWriteLock();
try
{
_internal.Clear();
_cachedHeaderAttributes.Clear();
}
finally
{
_internalDictionaryLock.ExitWriteLock();
}
}
/// <summary>
/// Access the stored values via the key.
/// </summary>
/// <param name="key">Attribute key</param>
/// <returns>Value</returns>
public virtual string this[string key]
{
set
{
_internalDictionaryLock.EnterWriteLock();
try
{
_internal[key] = value;
if (_cachedHeaderAttributes.ContainsKey(key))
{
_cachedHeaderAttributes.Remove(key);
}
}
finally
{
_internalDictionaryLock.ExitWriteLock();
}
}
get
{
_internalDictionaryLock.EnterReadLock();
try
{
if (_internal.ContainsKey(key))
{
return _internal[key];
}
}
finally
{
_internalDictionaryLock.ExitReadLock();
}
if (key == KEY_ISPERSISTENT)
{
// this is to prevent a Exception when the IsPersistent attribute
// hadn't been set in advance
return XmlHelper.XmlConvertValueToString(false);
}
throw new EventObjectException(1167, key);
}
}
/// <summary>
/// Remove a stored value by its key.
/// If the key was not found, <code>null</code> is returned.
/// </summary>
/// <param name="key">Attribute key</param>
/// <returns>The value of the element which was removed</returns>
public virtual string Remove(string key)
{
string retVal;
_internalDictionaryLock.EnterWriteLock();
try
{
_internal.TryGetValue(key, out retVal);
_internal.Remove(key);
if (_cachedHeaderAttributes.ContainsKey(key))
{
_cachedHeaderAttributes.Remove(key);
}
}
finally
{
_internalDictionaryLock.ExitWriteLock();
}
return retVal;
}
/// <summary>
/// Get a collection of the stored keys inside the header.
/// </summary>
public virtual ICollection<string> Keys
{
get
{
_internalDictionaryLock.EnterReadLock();
try
{
return _internal.Keys;
}
finally
{
_internalDictionaryLock.ExitReadLock();
}
}
}
/// <summary>
/// Check if the header contains a specific element.
/// </summary>
/// <param name="key">Attribute key</param>
/// <returns>true, if the header contains a value for this key</returns>
public virtual bool ContainsKey(string key)
{
_internalDictionaryLock.EnterReadLock();
bool retVal;
try
{
retVal = _internal.ContainsKey(key);
}
finally
{
_internalDictionaryLock.ExitReadLock();
}
return retVal;
}
/// <summary>
/// Read only property which counts the elements in the header.
/// </summary>
public virtual int Count
{
get
{
_internalDictionaryLock.EnterReadLock();
int retVal;
try
{
retVal = _internal.Count;
}
finally
{
_internalDictionaryLock.ExitReadLock();
}
return retVal;
}
}
/// <summary>
/// Get a stored element casted to a specific type.
/// if the value is not found, the default of this type is returned.
/// </summary>
/// <typeparam name="T">Runtime type of the value</typeparam>
/// <param name="key">Attribute key</param>
/// <returns>RuntimeType safe value</returns>
public virtual T GetValueAs<T>(String key)
{
try
{
if (_cachedHeaderAttributes.ContainsKey(key))
{
Object obj = _cachedHeaderAttributes[key];
if (obj is T)
{
return (T) obj;
}
}
String value = this[key];
return XmlHelper.XmlConvertStringToValue<T>(value);
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
}
/// <summary>
/// Add a new element with a specific key.
/// </summary>
/// <param name="key">Attribute key</param>
/// <param name="value">Value</param>
public virtual void Add(String key, String value)
{
Add(key, value, false);
}
/// <summary>
/// Add a new element with a specific key.
/// </summary>
/// <typeparam name="T">Optional runtime type parameter</typeparam>
/// <param name="key">Attribute key</param>
/// <param name="value">Value</param>
public virtual void Add<T>(String key, T value)
{
Add(key, value, false);
}
/// <summary>
/// Set a value for a specific key.
/// If the key was already used, the value is overwritten and the old one is returned.
/// </summary>
/// <typeparam name="T">Optional runtime type parameter</typeparam>
/// <param name="key">Attribute key</param>
/// <param name="value">Value</param>
/// <returns>The old value if it exists</returns>
public virtual string SetValue<T>(String key, T value)
{
string retVal = null;
_internalDictionaryLock.EnterWriteLock();
try
{
if (_internal.ContainsKey(key))
{
retVal = _internal[key];
}
_internal.Remove(key);
_internal.Add(key, XmlHelper.XmlConvertValueToString(value));
_cachedHeaderAttributes[key] = value;
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
finally
{
_internalDictionaryLock.ExitWriteLock();
}
return retVal;
}
// generic add value to the header
protected virtual void Add<T>(String key, T value, bool overwrite)
{
_internalDictionaryLock.EnterWriteLock();
try
{
if (overwrite)
{
_internal.Remove(key);
}
_internal.Add(key, XmlHelper.XmlConvertValueToString(value));
_cachedHeaderAttributes[key] = value;
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
finally
{
_internalDictionaryLock.ExitWriteLock();
}
}
#region ISerializable Members
/// <summary>
/// Create a new instance from the serialization stream.
/// </summary>
/// <param name="info">Serializer information</param>
/// <param name="context">Serialization stream context</param>
protected EventObjectHeader(SerializationInfo info, StreamingContext context)
{
_internal =
info.GetValue("headerAttributes", typeof (Dictionary<string, string>)) as Dictionary<string, string>;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("headerAttributes", _internal);
}
#endregion
}
}
All access to the _internal dictionary is protected by a ReaderWriterLockSlim - thus I can't see any possible concurrency issue.
With dotPeek I digged into the Dictionary class. Its ContainsKey method just returns this.FindEntry(key) >= 0, the FindEntry method looks like this:
private int FindEntry(TKey key)
{
if ((object) key == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
if (this.buckets != null)
{
int num = this.comparer.GetHashCode(key) & int.MaxValue;
for (int index = this.buckets[num % this.buckets.Length]; index >= 0; index = this.entries[index].next)
{
if (this.entries[index].hashCode == num && this.comparer.Equals(this.entries[index].key, key))
return index;
}
}
return -1;
}
And the GenericEqualityComparer's GetHashCode method looks like that:
public override int GetHashCode(T obj)
{
if ((object) obj == null)
return 0;
else
return obj.GetHashCode();
}
In the end, all I'm doing is a simple ContainsKey on a Dictionary<string, string>. I have no explanation for the NRE, but it seems to happen regularly in one of our customer's productive system. What could possibly explain the NullReferenceException?

Is there a simple way to avoid or stop FileSystemWatcher raise event twice in C#?

I want to know what how to avoid or stop FileSystemWatcher raise event twice in C#? I have a solution that will detect everytime if there is newly created xml file from a folder. I test my application using creating xml file using notepad but from the listbox it displays twice.
How can I fix this issue?
Here is my code:
private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
try
{
fileSystemWatcher1.EnableRaisingEvents = false;
listBox1.Items.Add(e.FullPath);
}
finally
{
fileSystemWatcher1.EnableRaisingEvents = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult dialogSelectFolder = folderBrowserDialog1.ShowDialog();
if (dialogSelectFolder.ToString() == "OK")
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
button2.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
fileSystemWatcher1.EnableRaisingEvents = true;
fileSystemWatcher1.Path = textBox1.Text;
fileSystemWatcher1.Filter = "*.xml";
}
private void button3_Click(object sender, EventArgs e)
{
button1.Enabled = true;
button3.Enabled = false;
textBox1.Text = "";
fileSystemWatcher1.EnableRaisingEvents = false;
}
}
I have stumbled upon this problem myself twice and i created a class that helps you get only one event at a time. You might also get false events when the file is not in read mode (such as when you copy a file).
You have to create a queue and store all events there and if a time interval passes then raise the appropriate event.
Unfortunately this is not a simple function thus i will include complete code.
using System;
using System.IO;
using System.Timers;
using System.Collections;
using System.ComponentModel;
namespace menelabs.core
{
/// <summary>
/// This class wraps FileSystemEventArgs and RenamedEventArgs objects and detection of duplicate events.
/// </summary>
internal class DelayedEvent
{
private readonly FileSystemEventArgs _args;
/// <summary>
/// Only delayed events that are unique will be fired.
/// </summary>
private bool _delayed;
public DelayedEvent(FileSystemEventArgs args)
{
_delayed = false;
_args = args;
}
public FileSystemEventArgs Args
{
get
{
return _args;
}
}
public bool Delayed
{
get
{
return _delayed;
}
set
{
_delayed = value;
}
}
public virtual bool IsDuplicate(object obj)
{
DelayedEvent delayedEvent = obj as DelayedEvent;
if (delayedEvent == null)
return false; // this is not null so they are different
FileSystemEventArgs eO1 = _args;
RenamedEventArgs reO1 = _args as RenamedEventArgs;
FileSystemEventArgs eO2 = delayedEvent._args;
RenamedEventArgs reO2 = delayedEvent._args as RenamedEventArgs;
// The events are equal only if they are of the same type (reO1 and reO2
// are both null or NOT NULL) and have all properties equal.
// We also eliminate Changed events that follow recent Created events
// because many apps create new files by creating an empty file and then
// they update the file with the file content.
return ((eO1 != null && eO2 != null && eO1.ChangeType == eO2.ChangeType
&& eO1.FullPath == eO2.FullPath && eO1.Name == eO2.Name) &&
((reO1 == null & reO2 == null) || (reO1 != null && reO2 != null &&
reO1.OldFullPath == reO2.OldFullPath && reO1.OldName == reO2.OldName))) ||
(eO1 != null && eO2 != null && eO1.ChangeType == WatcherChangeTypes.Created
&& eO2.ChangeType == WatcherChangeTypes.Changed
&& eO1.FullPath == eO2.FullPath && eO1.Name == eO2.Name);
}
}
/// <summary>
/// This class wraps a FileSystemWatcher object. The class is not derived
/// from FileSystemWatcher because most of the FileSystemWatcher methods
/// are not virtual. The class was designed to resemble FileSystemWatcher class
/// as much as possible so that you can use FileSystemSafeWatcher instead
/// of FileSystemWatcher objects.
/// FileSystemSafeWatcher will capture all events from the FileSystemWatcher object.
/// The captured events will be delayed by at least ConsolidationInterval milliseconds in order
/// to be able to eliminate duplicate events. When duplicate events are found, the last event
/// is droped and the first event is fired (the reverse is not recomended because it could
/// cause some events not be fired at all since the last event will become the first event and
/// it won't fire a if a new similar event arrives imediately afterwards).
/// </summary>
internal class FileSystemSafeWatcher
{
private readonly FileSystemWatcher _fileSystemWatcher;
/// <summary>
/// Lock order is _enterThread, _events.SyncRoot
/// </summary>
private readonly object _enterThread = new object(); // Only one timer event is processed at any given moment
private ArrayList _events;
private Timer _serverTimer;
private int _consolidationInterval = 1000; // milliseconds
#region Delegate to FileSystemWatcher
public FileSystemSafeWatcher()
{
_fileSystemWatcher = new FileSystemWatcher();
Initialize();
}
public FileSystemSafeWatcher(string path)
{
_fileSystemWatcher = new FileSystemWatcher(path);
Initialize();
}
public FileSystemSafeWatcher(string path, string filter)
{
_fileSystemWatcher = new FileSystemWatcher(path, filter);
Initialize();
}
/// <summary>
/// Gets or sets a value indicating whether the component is enabled.
/// </summary>
/// <value>true if the component is enabled; otherwise, false. The default is false. If you are using the component on a designer in Visual Studio 2005, the default is true.</value>
public bool EnableRaisingEvents
{
get
{
return _fileSystemWatcher.EnableRaisingEvents;
}
set
{
_fileSystemWatcher.EnableRaisingEvents = value;
if (value)
{
_serverTimer.Start();
}
else
{
_serverTimer.Stop();
_events.Clear();
}
}
}
/// <summary>
/// Gets or sets the filter string, used to determine what files are monitored in a directory.
/// </summary>
/// <value>The filter string. The default is "*.*" (Watches all files.)</value>
public string Filter
{
get
{
return _fileSystemWatcher.Filter;
}
set
{
_fileSystemWatcher.Filter = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether subdirectories within the specified path should be monitored.
/// </summary>
/// <value>true if you want to monitor subdirectories; otherwise, false. The default is false.</value>
public bool IncludeSubdirectories
{
get
{
return _fileSystemWatcher.IncludeSubdirectories;
}
set
{
_fileSystemWatcher.IncludeSubdirectories = value;
}
}
/// <summary>
/// Gets or sets the size of the internal buffer.
/// </summary>
/// <value>The internal buffer size. The default is 8192 (8K).</value>
public int InternalBufferSize
{
get
{
return _fileSystemWatcher.InternalBufferSize;
}
set
{
_fileSystemWatcher.InternalBufferSize = value;
}
}
/// <summary>
/// Gets or sets the type of changes to watch for.
/// </summary>
/// <value>One of the System.IO.NotifyFilters values. The default is the bitwise OR combination of LastWrite, FileName, and DirectoryName.</value>
/// <exception cref="System.ArgumentException">The value is not a valid bitwise OR combination of the System.IO.NotifyFilters values.</exception>
public NotifyFilters NotifyFilter
{
get
{
return _fileSystemWatcher.NotifyFilter;
}
set
{
_fileSystemWatcher.NotifyFilter = value;
}
}
/// <summary>
/// Gets or sets the path of the directory to watch.
/// </summary>
/// <value>The path to monitor. The default is an empty string ("").</value>
/// <exception cref="System.ArgumentException">The specified path contains wildcard characters.-or- The specified path contains invalid path characters.</exception>
public string Path
{
get
{
return _fileSystemWatcher.Path;
}
set
{
_fileSystemWatcher.Path = value;
}
}
/// <summary>
/// Gets or sets the object used to marshal the event handler calls issued as a result of a directory change.
/// </summary>
/// <value>The System.ComponentModel.ISynchronizeInvoke that represents the object used to marshal the event handler calls issued as a result of a directory change. The default is null.</value>
public ISynchronizeInvoke SynchronizingObject
{
get
{
return _fileSystemWatcher.SynchronizingObject;
}
set
{
_fileSystemWatcher.SynchronizingObject = value;
}
}
/// <summary>
/// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is changed.
/// </summary>
public event FileSystemEventHandler Changed;
/// <summary>
/// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is created.
/// </summary>
public event FileSystemEventHandler Created;
/// <summary>
/// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is deleted.
/// </summary>
public event FileSystemEventHandler Deleted;
/// <summary>
/// Occurs when the internal buffer overflows.
/// </summary>
public event ErrorEventHandler Error;
/// <summary>
/// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is renamed.
/// </summary>
public event RenamedEventHandler Renamed;
/// <summary>
/// Begins the initialization of a System.IO.FileSystemWatcher used on a form or used by another component. The initialization occurs at run time.
/// </summary>
public void BeginInit()
{
_fileSystemWatcher.BeginInit();
}
/// <summary>
/// Releases the unmanaged resources used by the System.IO.FileSystemWatcher and optionally releases the managed resources.
/// </summary>
public void Dispose()
{
Uninitialize();
}
/// <summary>
/// Ends the initialization of a System.IO.FileSystemWatcher used on a form or used by another component. The initialization occurs at run time.
/// </summary>
public void EndInit()
{
_fileSystemWatcher.EndInit();
}
/// <summary>
/// Raises the System.IO.FileSystemWatcher.Changed event.
/// </summary>
/// <param name="e">A System.IO.FileSystemEventArgs that contains the event data.</param>
protected void OnChanged(FileSystemEventArgs e)
{
if (Changed != null)
Changed(this, e);
}
/// <summary>
/// Raises the System.IO.FileSystemWatcher.Created event.
/// </summary>
/// <param name="e">A System.IO.FileSystemEventArgs that contains the event data.</param>
protected void OnCreated(FileSystemEventArgs e)
{
if (Created != null)
Created(this, e);
}
/// <summary>
/// Raises the System.IO.FileSystemWatcher.Deleted event.
/// </summary>
/// <param name="e">A System.IO.FileSystemEventArgs that contains the event data.</param>
protected void OnDeleted(FileSystemEventArgs e)
{
if (Deleted != null)
Deleted(this, e);
}
/// <summary>
/// Raises the System.IO.FileSystemWatcher.Error event.
/// </summary>
/// <param name="e">An System.IO.ErrorEventArgs that contains the event data.</param>
protected void OnError(ErrorEventArgs e)
{
if (Error != null)
Error(this, e);
}
/// <summary>
/// Raises the System.IO.FileSystemWatcher.Renamed event.
/// </summary>
/// <param name="e">A System.IO.RenamedEventArgs that contains the event data.</param>
protected void OnRenamed(RenamedEventArgs e)
{
if (Renamed != null)
Renamed(this, e);
}
/// <summary>
/// A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor.
/// </summary>
/// <param name="changeType">The System.IO.WatcherChangeTypes to watch for.</param>
/// <returns>A System.IO.WaitForChangedResult that contains specific information on the change that occurred.</returns>
public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType)
{
//TODO
throw new NotImplementedException();
}
/// <summary>
/// A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor
/// and the time (in milliseconds) to wait before timing out.
/// </summary>
/// <param name="changeType">The System.IO.WatcherChangeTypes to watch for.</param>
/// <param name="timeout">The time (in milliseconds) to wait before timing out.</param>
/// <returns>A System.IO.WaitForChangedResult that contains specific information on the change that occurred.</returns>
public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout)
{
//TODO
throw new NotImplementedException();
}
#endregion
#region Implementation
private void Initialize()
{
_events = ArrayList.Synchronized(new ArrayList(32));
_fileSystemWatcher.Changed += new FileSystemEventHandler(this.FileSystemEventHandler);
_fileSystemWatcher.Created += new FileSystemEventHandler(this.FileSystemEventHandler);
_fileSystemWatcher.Deleted += new FileSystemEventHandler(this.FileSystemEventHandler);
_fileSystemWatcher.Error += new ErrorEventHandler(this.ErrorEventHandler);
_fileSystemWatcher.Renamed += new RenamedEventHandler(this.RenamedEventHandler);
_serverTimer = new Timer(_consolidationInterval);
_serverTimer.Elapsed += new ElapsedEventHandler(this.ElapsedEventHandler);
_serverTimer.AutoReset = true;
_serverTimer.Enabled = _fileSystemWatcher.EnableRaisingEvents;
}
private void Uninitialize()
{
if (_fileSystemWatcher != null)
_fileSystemWatcher.Dispose();
if (_serverTimer != null)
_serverTimer.Dispose();
}
private void FileSystemEventHandler(object sender, FileSystemEventArgs e)
{
_events.Add(new DelayedEvent(e));
}
private void ErrorEventHandler(object sender, ErrorEventArgs e)
{
OnError(e);
}
private void RenamedEventHandler(object sender, RenamedEventArgs e)
{
_events.Add(new DelayedEvent(e));
}
private void ElapsedEventHandler(Object sender, ElapsedEventArgs e)
{
// We don't fire the events inside the lock. We will queue them here until
// the code exits the locks.
Queue eventsToBeFired = null;
if (System.Threading.Monitor.TryEnter(_enterThread))
{
// Only one thread at a time is processing the events
try
{
eventsToBeFired = new Queue(32);
// Lock the collection while processing the events
lock (_events.SyncRoot)
{
DelayedEvent current;
for (int i = 0; i < _events.Count; i++)
{
current = _events[i] as DelayedEvent;
if (current.Delayed)
{
// This event has been delayed already so we can fire it
// We just need to remove any duplicates
for (int j = i + 1; j < _events.Count; j++)
{
if (current.IsDuplicate(_events[j]))
{
// Removing later duplicates
_events.RemoveAt(j);
j--; // Don't skip next event
}
}
bool raiseEvent = true;
if (current.Args.ChangeType == WatcherChangeTypes.Created || current.Args.ChangeType == WatcherChangeTypes.Changed)
{
//check if the file has been completely copied (can be opened for read)
FileStream stream = null;
try
{
stream = File.Open(current.Args.FullPath, FileMode.Open, FileAccess.Read, FileShare.None);
// If this succeeds, the file is finished
}
catch (IOException)
{
raiseEvent = false;
}
finally
{
if (stream != null) stream.Close();
}
}
if (raiseEvent)
{
// Add the event to the list of events to be fired
eventsToBeFired.Enqueue(current);
// Remove it from the current list
_events.RemoveAt(i);
i--; // Don't skip next event
}
}
else
{
// This event was not delayed yet, so we will delay processing
// this event for at least one timer interval
current.Delayed = true;
}
}
}
}
finally
{
System.Threading.Monitor.Exit(_enterThread);
}
}
// else - this timer event was skipped, processing will happen during the next timer event
// Now fire all the events if any events are in eventsToBeFired
RaiseEvents(eventsToBeFired);
}
public int ConsolidationInterval
{
get
{
return _consolidationInterval;
}
set
{
_consolidationInterval = value;
_serverTimer.Interval = value;
}
}
protected void RaiseEvents(Queue deQueue)
{
if ((deQueue != null) && (deQueue.Count > 0))
{
DelayedEvent de;
while (deQueue.Count > 0)
{
de = deQueue.Dequeue() as DelayedEvent;
switch (de.Args.ChangeType)
{
case WatcherChangeTypes.Changed:
OnChanged(de.Args);
break;
case WatcherChangeTypes.Created:
OnCreated(de.Args);
break;
case WatcherChangeTypes.Deleted:
OnDeleted(de.Args);
break;
case WatcherChangeTypes.Renamed:
OnRenamed(de.Args as RenamedEventArgs);
break;
}
}
}
}
#endregion
}
}
You may find the code at:
https://github.com/melenaos/FileSystemSafeWatcher/blob/master/FileSystemSafeWatcher.cs

can't get value of trackbar on menu strip

I've added a trackbar to menu strip manually because vs 2008 doesn't allow me to do.
However, i can't get the value of trackbar.
Form1.cs:
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.MenuStrip |
ToolStripItemDesignerAvailability.ContextMenuStrip)]
public class TrackBarMenuItem : ToolStripControlHost
{
private TrackBar trackBar;
public TrackBarMenuItem()
: base(new TrackBar())
{
this.trackBar = this.Control as TrackBar;
trackBar.TickFrequency = 1;
trackBar.Maximum = 255;
trackBar.LargeChange = 5;
trackBar.SmallChange = 2;
}
}
Form1.Designer.cs:
private TrackBarMenuItem trackBar1;
//
// trackBar1
//
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(104, 25);
and this is how i need to use it:
private void trackBar1_Scroll(object sender, System.EventArgs e)
{
int valueB = trackBar1.Value;
pictureBox2.Image = Deneme(new Bitmap(pictureBox1.Image),valueB);
}
but i get this error:
Error 1 'goruntuIsleme2.Form1.TrackBarMenuItem' does not contain a
definition for 'Value' and no extension method 'Value' accepting a
first argument of type 'goruntuIsleme2.Form1.TrackBarMenuItem' could
be found (are you missing a using directive or an assembly reference?)
any ideas?
Expose the value of the internal Trackbar object as a property on your new TrackBarMenuItem class:
Value { get { return trackBar.Value; } set { trackBar.Value = value; } }
i am adding the solution i found. someone might need it:
[System.ComponentModel.DesignerCategory("code")]
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ContextMenuStrip | ToolStripItemDesignerAvailability.MenuStrip)]
public partial class ToolStripMenuItem : ToolStripControlHost
{
public ToolStripMenuItem()
: base(CreateControlInstance())
{
}
/// <summary>
/// Create a strongly typed property called TrackBar - handy to prevent casting everywhere.
/// </summary>
public TrackBar TrackBar
{
get
{
return Control as TrackBar;
}
}
/// <summary>
/// Create the actual control, note this is static so it can be called from the
/// constructor.
///
/// </summary>
/// <returns></returns>
private static Control CreateControlInstance()
{
TrackBar t = new TrackBar();
t.AutoSize = false;
t.Height = 16;
t.Maximum = 255;
// Add other initialization code here.
return t;
}
[DefaultValue(0)]
public int Value
{
get { return TrackBar.Value; }
set { TrackBar.Value = value; }
}
/// <summary>
/// Attach to events we want to re-wrap
/// </summary>
/// <param name="control"></param>
protected override void OnSubscribeControlEvents(Control control)
{
base.OnSubscribeControlEvents(control);
TrackBar trackBar = control as TrackBar;
trackBar.ValueChanged += new EventHandler(trackBar_ValueChanged);
}
/// <summary>
/// Detach from events.
/// </summary>
/// <param name="control"></param>
protected override void OnUnsubscribeControlEvents(Control control)
{
base.OnUnsubscribeControlEvents(control);
TrackBar trackBar = control as TrackBar;
trackBar.ValueChanged -= new EventHandler(trackBar_ValueChanged);
}
/// <summary>
/// Routing for event
/// TrackBar.ValueChanged -> ToolStripTrackBar.ValueChanged
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void trackBar_ValueChanged(object sender, EventArgs e)
{
// when the trackbar value changes, fire an event.
if (this.ValueChanged != null)
{
ValueChanged(sender, e);
}
}
// add an event that is subscribable from the designer.
public event EventHandler ValueChanged;
// set other defaults that are interesting
protected override Size DefaultSize
{
get
{
return new Size(200, 16);
}
}
}
if you add this to your code, you will be able to add trackbars as ToolStripMenuItem via Designer.
Does your class TrackBarMenuItem has a property called Value? If not, you have to add it.

Implementing an observer pattern with winforms

I have one collection of objects that many of my forms (using WeifenLuo.WinFormsUI.Docking) need to interact with.
i.e. If the collection has an addition (or deletion) made in one form, then the other forms respond by refreshing their views.
Obviously, an observer pattern would be a good candidate here. However, I am having issues trying to implement this in my program.
First, it seemed best to create an observer class for my collection like so:
public class DataCollectionObserver : Form
{
internal static void DataCollectionRegister(DataCollection dataCollection)
{
dataCollection.ImageAdded += new EventHandler(dataAdded);
dataCollection.ImageRemoved += new EventHandler(dataRemoved);
dataCollection.ImageIndexChanged += new EventHandler(dataIndexChanged);
dataCollection.ImageListCleared += new EventHandler(dataListCleared);
}
internal static void DataCollectionUnRegister(DataCollection dataCollection)
{
dataCollection.ImageAdded -= new EventHandler(dataAdded);
dataCollection.ImageRemoved -= new EventHandler(dataRemoved);
dataCollection.ImageIndexChanged -= new EventHandler(dataIndexChanged);
dataCollection.ImageListCleared -= new EventHandler(dataListCleared);
}
internal static void dataAdded(object sender, EventArgs e) {}
internal static void dataRemoved(object sender, EventArgs e) {}
internal static void dataIndexChanged(object sender, EventArgs e) {}
internal static void dataListCleared(object sender, EventArgs e) {}
}
Then override the base event handlers in the subclassed forms?
But, I cannot do this and use the WeifenLuo.WinFormsUI.Docking library...
Well, I could have DataCollectionObserver inherit DockContent from WeifenLuo.WinFormsUI.Docking, but that creates a situation where I need to have two DataCollectionObserver classes -
one which inherits Form and another that inherits DockContent :-[
or, I could make the DataCollectionObserver an Interface, but that still leaves me with duplicate code laying about...
So, does anyone have a suggestion here? Am I missing something obvious, or is this a situation where duplication of code 'must be done' for the sake of simplicity?
Edit://
I am not having problems getting notification in my forms. As a matter of fact, the whole thing is working right now. The reason that I am asking is because the whole thing "smells" due to the block copy and paste of code in these four different forms that I have which subscribe to the collection events and unsubscribe on Form.Closing().
What I would like to do is implement the behavior that I have copied and pasted to these four forms in one place and have the forms that should receive collection change notifications implement that behavior as needed.
Hope that makes things clearer?
FWIW, this is my collection class:
using System;
using System.Collections;
using System.Reflection;
namespace MyNameSpace.Collections
{
/// <summary>
/// Generic Collection of Objects with Events
/// </summary>
public class CollectionWithEvents<T> : CollectionBase
{
public bool SuppressEventNotification
{
get;
set;
}
public CollectionWithEvents()
{
SuppressEventNotification = false;
}
#region Events
/// <summary>
/// Raises before an item is added to the list.
/// </summary>
public event EventHandler<ItemEventArgs<T>> BeforeItemAdded;
/// <summary>
/// Raises when an item is added to the list.
/// </summary>
public event EventHandler<ItemEventArgs<T>> ItemAdded;
/// <summary>
/// Raises before a collection of items is added to the list.
/// </summary>
public event EventHandler<ItemsEventArgs<T>> BeforeItemsAdded;
/// <summary>
/// Raises when a collection of items is added to the list.
/// </summary>
public event EventHandler<ItemsEventArgs<T>> ItemsAdded;
/// <summary>
/// Raises before an item is changed in the list.
/// </summary>
public event EventHandler<ItemEventArgs<T>> BeforeItemChanged;
/// <summary>
/// Raises when an item is changed in the list.
/// </summary>
public event EventHandler<ItemEventArgs<T>> ItemChanged;
/// <summary>
/// Raises before an item is removed from the list.
/// </summary>
public event EventHandler<ItemEventArgs<T>> BeforeItemRemoved;
/// <summary>
/// Raises when an item is removed from the list.
/// </summary>
public event EventHandler<ItemEventArgs<T>> ItemRemoved;
/// <summary>
/// Raises when the items are cleared from the list.
/// </summary>
public event EventHandler<EventArgs> ItemsCleared;
#endregion
public T this[int index]
{
get { return (T)this.List[index]; }
set
{
if (!SuppressEventNotification)
{
OnBeforeItemChanged(this, new ItemEventArgs<T>(value));
}
this.List[index] = value;
if (!SuppressEventNotification)
{
OnItemChanged(this, new ItemEventArgs<T>(value));
}
}
}
public int Add(T item)
{
if (!SuppressEventNotification)
{
OnBeforeItemAdded(this, new ItemEventArgs<T>(item));
}
int retValue = this.List.Add(item);
if (!SuppressEventNotification)
{
OnItemAdded(this, new ItemEventArgs<T>(item));
}
return retValue;
}
public void AddRange(Collection<T> collection)
{
T[] tmp = new T[collection.Count];
collection.CopyTo(tmp, 0);
AddRange(tmp);
}
public void AddRange(T[] collection)
{
if (!SuppressEventNotification)
{
OnBeforeItemsAdded(this, new ItemsEventArgs<T>(collection));
}
this.AddRange(collection);
if (!SuppressEventNotification)
{
OnItemsAdded(this, new ItemsEventArgs<T>(collection));
}
}
public bool Contains(T item)
{
return this.List.Contains(item);
}
public void CopyTo(Array array, int index)
{
this.List.CopyTo(array, index);
}
public int IndexOf(T item)
{
return this.List.IndexOf(item);
}
public void Insert(int index, T item)
{
this.List.Insert(index, item);
}
public void Remove(T item)
{
if (!SuppressEventNotification)
{
OnBeforeItemRemoved(this, new ItemEventArgs<T>(item));
}
T tmp = (T)item;
this.List.Remove(item);
if (!SuppressEventNotification)
{
OnItemRemoved(this, new ItemEventArgs<T>(tmp));
}
tmp = default(T);
}
public void Sort(string Property, Common.SortOrder Order)
{
Common.GenericComparer genericComparer = new Common.GenericComparer(Property, Order);
this.InnerList.Sort(genericComparer);
}
#region Event Methods
/// <summary>
/// Raised before an Item is added to the list.
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">ItemEventArgs</param>
protected virtual void OnBeforeItemAdded(object sender, ItemEventArgs<T> e)
{
if (BeforeItemAdded != null)
{
BeforeItemAdded(sender, e);
}
}
/// <summary>
/// Raised when an Item is added to the list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">ItemEventArgs</param>
protected virtual void OnItemAdded(object sender, ItemEventArgs<T> e)
{
if (ItemAdded != null)
{
ItemAdded(sender, e);
}
}
/// <summary>
/// Raised before a collection of Items is added to the list.
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">ItemEventArgs</param>
protected virtual void OnBeforeItemsAdded(object sender, ItemsEventArgs<T> e)
{
if (BeforeItemsAdded != null)
{
BeforeItemsAdded(sender, e);
}
}
/// <summary>
/// Raised when a collection of Items is added to the list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">ItemEventArgs</param>
protected virtual void OnItemsAdded(object sender, ItemsEventArgs<T> e)
{
if (ItemsAdded != null)
{
ItemsAdded(sender, e);
}
}
/// <summary>
/// Raised before an Item is changed to the list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">GenericItemEventArgs</param>
protected virtual void OnBeforeItemChanged(object sender, ItemEventArgs<T> e)
{
if (BeforeItemChanged != null)
{
BeforeItemChanged(sender, e);
}
}
/// <summary>
/// Raised when an Item is changed to the list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">ItemEventArgs</param>
protected virtual void OnItemChanged(object sender, ItemEventArgs<T> e)
{
if (ItemChanged != null)
{
ItemChanged(sender, e);
}
}
/// <summary>
/// Raised before an Item is removed from the list.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">ItemEventArgs</param>
protected virtual void OnBeforeItemRemoved(object sender, ItemEventArgs<T> e)
{
if (BeforeItemRemoved != null)
{
BeforeItemRemoved(sender, e);
}
}
/// <summary>
/// Raised when an Item is removed from the list.
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">ItemEventsArgs</param>
protected virtual void OnItemRemoved(object sender, ItemEventArgs<T> e)
{
if (ItemRemoved != null)
{
ItemRemoved(sender, e);
}
}
/// <summary>
/// Raised when the Items are cleared from this list.
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">EventArgs</param>
protected virtual void OnItemsCleared(object sender, EventArgs e)
{
if (ItemsCleared != null)
{
ItemsCleared(sender, e);
}
}
#endregion
}
public class ItemEventArgs<T> : EventArgs
{
/// <summary>
/// Item
/// </summary>
public T Item { get; private set; }
/// <summary>
/// Default constructor
/// </summary>
/// <param name="Item"></param>
public ItemEventArgs(T Item)
{
this.Item = Item;
}
}
public class ItemsEventArgs<T> : EventArgs
{
/// <summary>
/// Items
/// </summary>
public T[] Items { get; private set; }
/// <summary>
/// Default constructor
/// </summary>
/// <param name="Items"></param>
public ItemsEventArgs(T[] Items)
{
this.Items = Items;
}
}
}
I might be mistaken. But you could do it this way and your inheritance problem would not be present. I'll try to give a simple example :
You collection class could be of this kind :
public class MyCollection
{
IList<string> MyList { get; set; }
public event EventHandler<StringEventArgs> OnAdded;
public event EventHandler<StringEventArgs> OnRemoved;
public MyCollection()
{
MyList = new List<string>();
}
public void Add(string s)
{
MyList.Add(s);
if (OnAdded != null)
OnAdded(this, new StringEventArgs() { StringAddedOrRemoved = s });
}
public void Remove(string s)
{
MyList.Remove(s);
if (OnRemoved != null)
OnRemoved(this, new StringEventArgs() { StringAddedOrRemoved = s });
}
}
Really simple class with two customized EventHandlers :
public class StringEventArgs : EventArgs
{
public string StringAddedOrRemoved;
public override string ToString()
{
return StringAddedOrRemoved;
}
}
Nothing hard to understand here and then based on the three forms you could use your forms this way.
The first one holds two buttons to interact with the collection and creates the two forms which will observe your collection :
public partial class Form1 : Form
{
public static MyCollection collection;
public Form1()
{
InitializeComponent();
collection = new MyCollection();
Form2 form2 = new Form2();
form2.Show();
Form3 form3 = new Form3();
form3.Show();
collection.OnAdded += form2.MyCollectionAdded;
collection.OnRemoved += form2.MyCollectionRemoved;
collection.OnAdded += form3.MyCollectionAdded;
collection.OnRemoved += form3.MyCollectionRemoved;
}
private void Add_Click(object sender, EventArgs e)
{
collection.Add("test add");
}
private void button1_Click(object sender, EventArgs e)
{
collection.Remove("test add");
}
}
The collection gets linked to each of the functions of the forms that will be observed here :
collection.OnAdded += form2.MyCollectionAdded;
collection.OnRemoved += form2.MyCollectionRemoved;
collection.OnAdded += form3.MyCollectionAdded;
collection.OnRemoved += form3.MyCollectionRemoved;
And so we need to implement those forms :
public partial class Form2 : Form
{
public string Name { get; set; }
public bool Flag { get; set; }
public Form2()
{
InitializeComponent();
}
public void MyCollectionAdded(object sender, StringEventArgs e)
{
//Some action
Flag = true;
label1.Text = string.Format("{0} has added {1} to its list, flag={2}", Name, e.StringAddedOrRemoved, Flag);
}
public void MyCollectionRemoved(object sender, StringEventArgs e)
{
//Some action
Flag = false;
label1.Text = string.Format("{0} has removed {1} from its list, flag={2}", Name, e.StringAddedOrRemoved, Flag);
}
}
I am inheriting my stuff from Form but it could be inherited form whatever you want actually. If you want to share some code among different forms, think of helper functions in a static class, or of whatever pattern that might suit your need.
Hope it helps a bit, and that I am not completely out of scope!
[EDIT] Oops didn't see the Edit, sorry pal![/EDIT]
Which version of .net ,you are using if it is >= 3.5 , you can make use of ObservableCollection to achive what ever you are doing
There is an 'ObservableCollection' in the Framework just for this type of thing. See here.

Categories

Resources