Intercepting the value change of SetChildIndex - winforms

In a .NET CF-form i have multiple panels. I want to have a property that should always be informed about if a panel is in the front.
Can this be done using the GetChildIndex() method?
If yes, how do i intercept the change to SetChildIndex()?
Thanks in advance

For everybody who is interested for future use:
simply add a new event handler for the Paint event of each panel, for example:
panel1.Paint += new PaintEventHandler(panel1_Paint);
panel2.Paint += new PaintEventHandler(panel2_Paint);
and in each of the event handlers just call a Method which retrieves the state of all the panels like so:
void panel2_Paint(object sender, PaintEventArgs e)
{
GetPanelStates();
}
void panel1_Paint(object sender, PaintEventArgs e)
{
GetPanelStates();
}
void GetPanelStates()
{
Panel2IsInFront = panel2.Parent.Controls.GetChildIndex(panel2) == 0;
Panel1IsInFront = panel1.Parent.Controls.GetChildIndex(panel1) == 0;
}

Related

Interact with the Ok/Accept Or Cancel Button of a RepositoryItemTimeSpanEdit?

as seen in this post, I need to interact with the button, I mean, save the value of the repository when the user press the OK button, any suggest?
You need to find your TimeSpanEdit control inside of the popup form. You can iterate through popupForm.Controls collection to find out the control with TimeSpanEdit type. Here is example of how to do it. After that you can use TimeSpanEdit.TimeSpan property to get the value of TimeSpanEdit control.
private void OkButton_Click(object sender, EventArgs e)
{
var popupForm = (TimeSpanEditDropDownForm)OwnedForms.FirstOrDefault(item => item is TimeSpanEditDropDownForm);
if (popupForm == null)
return;
var timeSpanEdit = GetAll(this, typeof(TimeSpanEdit)).FirstOrDefault();
if (timeSpanEdit == null)
return;
MessageBox.Show(timeSpanEdit.TimeSpan.ToString());
}
public IEnumerable<Control> GetAll(Control control,Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl,type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
I think you can use object sender. sender will contains probably TimeSpanEditDropDownForm and there you should get actual value of this form. :)
I presume this code is called from controller is it?
if it is true than you have View.CurrentObject and you must know which property uses this TimeSpanEditDropDownForm so you could do something like this.
private void OkButton_Click(object sender, EventArgs e)
{
MyClass myClass = View.CUrrentObject as MyClass;
TimeSpanEditDropDownForm timeSpanForm = sender as TimeSpanEditDropDownForm;
myClass.CurrentTime = timeSpanForm.CurrentTime;
myClass.Session.CommitChanges();
MessageBox.Show("Ok");
}
I dont know what is name of right attribute wich store TimeSpan inside TimeSpanEditDropDownForm thats thing you must find out but I think it could helps :)

Working with ProgressBar and ComboBox

I'm in trouble with a Marquee ProgressBar. I need to execute a method (refreshList()) to get a List<string>. Then I assign this List to a ComboBox, so ComboBox refreshes with the new Items. As refreshList() take 3 or 4 sec, I wanted to run a Marquee ProgressBar. But I couldn't. ProgressBar is ok, but ComboBox doesn't load new Items.
My refreshList() method:
private void refreshList(List<string> list)
{
albumList.DataSource = null;
albumList.DataSource = list;
}
I have the following code, it works fine:
private void changeDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
fbd.RootFolder = Environment.SpecialFolder.MyComputer;
folderPath = "";
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
folderPath = fbd.SelectedPath;
refreshList(N.getList(folderPath));
}
}
But I added a ProgressBar and wrote this code:
private void changeDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
fbd.RootFolder = Environment.SpecialFolder.MyComputer;
folderPath = "";
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
folderPath = fbd.SelectedPath;
bgWorker.WorkerReportsProgress = true;
bgWorker.RunWorkerAsync();
}
}
And I placed refreshList() in doWork() method:
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
refreshList(N.getList(folderPath));
}
But unfortunately this isn't working. Can anybody help me solving this problem? Thanks in advance.
You can use the MarqueeAnimationSpeed and Value properties of the ProgressBar control to stop and start the Marquee. There's no need to use WorkerReportsProgress* as you aren't incrementing a normal progress bar - you just want to "spin" the Marquee.
You can do something like the following:
public Form1()
{
InitializeComponent();
//Stop the progress bar to begin with
progressBar1.MarqueeAnimationSpeed = 0;
//If you wire up the event handler in the Designer, then you don't need
//the following line of code (the designer adds it to InitializeComponent)
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
private void changeDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
fbd.RootFolder = Environment.SpecialFolder.MyComputer;
folderPath = "";
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
folderPath = fbd.SelectedPath;
//This line effectively starts the progress bar
progressBar1.MarqueeAnimationSpeed = 10;
bgWorker.RunWorkerAsync(); //Calls the DoWork event
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = N.getList(folderPath); //Technically this is the only work you need to do in the background
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//these two lines effectively stop the progress bar
progressBar1.Value = 0;
progressBar1.MarqueeAnimationSpeed = 0;
//Now update the list with the result from the work done on the background thread
RefreshList(e.Result as List<String>);
}
private void RefreshList(List<String> results)
{
albumList.DataSource = null; //You don't need this line but there is no real harm.
albumList.DataSource = list;
}
Remember to wire up the RunWorkerCompleted event to backgroundWorker1_RunWorkerCompleted via the Properties bar, Events section in the designer.
To begin with, we start the ProgressBar's animation by setting the MarqueeAnimationSpeed property to a non-zero positive number as part of your successful folder selection.
Then, after calling RunWorkerAsync, the code builds your list in the DoWork method, then assigns the result to the DoWorkEventArgs, which get passed to the RunWorkerCompleted event (which fires when DoWork is finished).
In the backgroundWorker1_RunWorkerCompleted method, we stop the progress bar (and set it's value to zero to effectively return it to it's original state), and then we pass the list to the refreshList method to databind it and populate the ComboBox.
Tested using VS2012, Windows Forms, .Net 4.0 (with a Thread.Sleep to emulate the time taken for N.getList)
*WorkerReportsProgress, and the associated ReportProgress method/event are used when you want to increment the progress bar - you can tell the GUI that you are 10% done, 20% done, 50% done etc etc.

How do I go about implementing drag delta on shapes

How do I go about implementing the drag delta on a Shape, I have the following code:
void Connector_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (e.ClickCount == 1)
{
this.Focus();
this.CaptureMouse();
this.RaiseEvent(new DragStartedEventArgs(0,0));
initMousePoint = e.GetPosition(this);
}
e.Handled = true;
}
void Shape2_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
currMousePoint = e.GetPosition(this);
if (this.IsMouseCaptured)
{
this.RaiseEvent(new DragDeltaEventArgs(0,0);
}
}
void Shape2_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
this.ReleaseMouseCapture();
}
Now for the DragDeltaEvent args do I need to compute the drag in the mousemove and pass it to the event, also is this the right way to raise the event. If this works, then I should only subscribe to the drag delta event and use it as a thumb? Note, I do not want to template the thumb with the shape, providing this answer won't help me.
note the chagnes, about the getting the position of the mouse, this I don't think works, because it gets the position relative to the element, not the containing panel, so I don't think i will be able to find the drag distance this way.
I solved it using:
currMousePoint = e.GetPosition(this);
double dragHorizontal = currMousePoint.X - initMousePoint.X;
double dragVertical = currMousePoint.Y - initMousePoint.Y;
//Set the new canvas top and left proeprties here.

Deselecting item from Silverlight datagrid if it's clicked twice

I have a Silverlight 4.0 datagrid, which has the SelectionMode set to Single. The problem with this is that users need to CTRL+Click on an already-selected row in order to deselect it (and have nothing selected in the grid). I'd like for them to be able to simply left-click on the already-selected row to have it deselected.
I tried doing this with a SelectionChanged event (inspecting the added items in the event arguments), however it didn't work because the event isn't thrown when the user clicks on the same row twice.
Any advice?
There is no way to capture the second event because it is never fired. What you could do is apply the type of customization used in this project to one that does capture the second click and fire the event a second time should you wish:
http://www.codeproject.com/KB/silverlight/doubleClickDataGridSL.aspx
I have the same task, so here is my solution:
attach handler for datagrid's MouseLeftButtonDown event using AddHandler dataGrid.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(DataGrid_MouseLeftButtonDown), true);
, save SelectedIndex in private variable
private int prevSelectedIndex;
void DataGrid_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (prevSelectedIndex != -1 && prevSelectedIndex == dataGrid.SelectedIndex)
{
dataGrid.SelectedIndex = -1;
}
prevSelectedIndex = dataGrid.SelectedIndex;
}
if you want reuse this logic you can create Behavior for DataGrid type
Add System.Windows.Interactivity assembly reference, add class DataGridSecondClickUnselectBehavior
public class DataGridSecondClickUnselectBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown), true);
}
private int prevSelectedIndex;
void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (prevSelectedIndex != -1 && prevSelectedIndex == AssociatedObject.SelectedIndex)
{
AssociatedObject.SelectedIndex = -1;
}
prevSelectedIndex = AssociatedObject.SelectedIndex;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.RemoveHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown));
}
}
Now after you compile solution in blend you can add this behavior simply Drag'n'drop from Assets->Behaviors to DataGrid control

Update GUI using BackgroundWorker

I've been searching and found that a good way to perform background work and update the GUI is using background workers. However, doing this (stupid) little task (counting from 1 to 10000) it doesn't update the label content but prints to the debug! (This is just a spike solution for another project of course...)
Here's the code:
public partial class MainWindow : Window
{
BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.WorkerReportsProgress = true;
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("DONE");
}
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Content = "going here: "+e.ProgressPercentage;
Debug.WriteLine(e.ProgressPercentage);
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i=0; i < 10000; i++)
{
bw.ReportProgress((i*100)/10000);
}
}
}
The ProgressChanged event is raised on the UI thread, not the worker thread. In your code, the worker thread is doing almost nothing (just loop from 0 to 10000 and call ReportProgress), most of the work is done on the UI thread. Basically, you're sending too many progress notifications. Because of this, the UI thread is almost always busy and has no time to render the new content of the label.
Rendering in WPF is not performed immediately when you change a property of a control, it is done on a separate dispatcher frame, which is processed when the dispatcher has nothing more urgent to do, based on the priority of the task. The priority used for rendering has a value of 7 (DispatcherPriority.Render); the ProgressChanged event is marshalled to the UI thread with a priority of 9 (DispatcherPriority.Normal), as specified on MSDN. So the ProgressChanged notifications always have a higher priority than rendering, and since they keep coming, the dispatcher never has time to process the rendering tasks.
If you just decrease the frequency of the notifications, your app should work fine (currently you're sending 100 notifications for each percentage value, which is useless):
void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10000; i++)
{
if (i % 100 == 0)
bw.ReportProgress(i / 100);
}
}
this.Dispatcher.BeginInvoke( (Action) delegate(){
label1.Content = "going here: "+e.ProgressPercentage;
});
Try to change the label using womething like this:
string Text = "going here: " + e.ProgressPercentage;
this.Invoke((MethodInvoker)delegate {
label1.Content = newText;
});
Note that i'm not sure it will work. I can not test it now. If it does not work, let me know and I will delete the answer.
If you need the a canonical way to do exactly what you want, look at the Hath answer in this post: How do I update the GUI from another thread?

Resources