C# Form/Control Width Not Updating All the Time - c#

I've made a small tool bar that sits in a transparent form, it loads a variable sized menu from a text file and can be changed on the fly. Each button is a type of Label, the bar is just a list of buttons and adds/removes them in the correct spots. Width of the form is only a little bigger than the menu bar so that sub menu isn't cut off
Everything is working sweet except, when I reload everything part of the toolbar is lost. I've attempted to change the width so many ways, I've cleared and removed the controls from the form, refreshing the form/menu, updating it etc however nothing seems to make it work as intended EXCEPT if I call the reload function twice in a row, it works. I can't see why calling it once doesn't work but calling it twice works.
I'm fine with calling reload twice in a row as it would only be called a couple times a week.
Question: what on earth is causing this?
photo of issues first photo shows what it should look like, second is after removing a menu button and reloading, third is after adding a button and reloading
//calling this.reload() doesn't work
//calling this.reload();this.reload() works
void reload(Object o = null, EventArgs e = null)
{
this._menuBar.clear();
this.loadFromFile();
}
void loadFromFile(Object o = null, EventArgs e = null)
{
try
{
if (File.Exists("kpi.txt"))
{
string cline = "", cmenu = "", lhs = "";
menuList mb = null;
StreamReader sr = new StreamReader("kpi.txt");
while (!sr.EndOfStream)
{
cline = sr.ReadLine(); //get current line
if (cline.Length > 0 && cline[0] != ';')
{
//check if main menu/command
if (cline[0] == '[')
{
cmenu = Regex.Match(cline, #"(?<=^\[)[a-zA-Z -\#_{-~\^\r\n]+(?=\])").Value;
if (cmenu != "")
{
mb = this._menuBar.addMenuButton(cmenu);
mb.data["options"] = Regex.Match(cline, #"\/\w+$").Value;
var match = Regex.Match(cline, #"(?<=<)([^>\[\]\r\n]+)(?=>)");
mb.data["count"] = (match.Success ? match.Value : "0");
mb.data["copy"] = "";
applyMenuOptions(mb, false);
}
}
//just a standard line
else
{
cline = cline.Trim();
lhs = Regex.Match(cline, #"^[^\;\<\[\]\r\n]+(?=$|\<|\;)").Value;
if (mb.getSubMenuItem(lhs) == null)
{
var newButton = mb.addSubMenu(lhs);
if (newButton != null)
{
newButton.parent = mb;
newButton.data["options"] = mb.data["options"];
newButton.data["copy"] = Regex.Match(cline, #"((?<=\;)[^\[\]\<\r\n]+(?=<|$))").Value;
var matches = Regex.Match(cline, #"(?<=<)([^>\[\]\r\n]+)(?=>)");
int intout = 0;
if (int.TryParse(matches.Value, out intout))
{//no description
newButton.data["description"] = "";
newButton.data["count"] = intout.ToString();
}
else
{
newButton.data["description"] = matches.Value;
newButton.data["count"] = (matches.NextMatch().Success ? matches.NextMatch().Value : "0");
}
applyMenuOptions(newButton);
newButton.addMiddleClick(this.addcopy);
if (newButton.data["options"].Contains("i"))
{
newButton.addRightClick(this.appendInfo);
newButton.addRightClick(this.increment);
}
}
}
}
}
}
sr.Close();
this._menuBar.squish();
this.Width = this._menuBar.Width+50;
}
else
{
menuList mb = this._menuBar.addMenuButton("menu");
mb.data["options"] = "\\m";
mb.data["count"] = "0";
mb.data["copy"] = "";
mb.data["description"] = "";
applyMenuOptions(mb, false);
saveDictonary();
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to load data " + ex);
//ILog log = LogManager.GetLogger(typeof(Program));
//log.Info(ex);
}
}
public menuList addMenuButton(string s, int w = 0, int h = 0, int x = -1, int y = -1)
{
menuList mb = new menuList(this._form, s);
if (this.menuItems.Exists(z => z.Text == s)) return null;
mb.Width = (w==0?settings.intOf("ButtonWidth"):w);
mb.Height = (h==0?settings.IntOf("ButtonHeight"):h);
if (x == -1 || y == -1)
mb.Location = new Point(this.menuItems.Count > 0 ? this.menuItems.Last().Location.X + this.menuItems.Last().Width : padding);
else mb.Location = new Point(x, y);
mb.BringToFront();
mb.Show();
this.menuItems.Add(mb);
// this.Refresh();
return mb;
}
internal void clear()
{
foreach(var i in this.menuItems)
{
this._form.Controls.Remove(i);
i.clear();
i.Dispose();
}
this.menuItems.Clear();
this._form.Controls.Remove(this);
this.menuItems = new List<menuList>();
this._form.Controls.Add(this);
}
internal void squish()
{
try
{
this.Width = (this.menuItems.Count * this.menuItems.First().Width) + (2 * padding);
}
catch(Exception ex) { MessageBox.Show(""+ex); }
}

Found the culprit, bother the button class and the tool bar class were both adding themselves to the form control instead of button class adding to the tool bar (picture box) controls!
Removing transparency showed the buttons not moving when the tool bar was moved!

Related

WPF window won't appear when using Show or ShowDialog

I'm a junior programmer.
A window of my WPF program won't show itself anymore. I can't seem to find out why.
My program has three different windows. When the first one shows up and I click on the button to start the rest of the program, it does run, it also goes through the code of the window that I want to see, but it does not show anything.
I hope that any of you can help.
Below are parts of my code. The first one should already call the window
private void SortingPartOne(){
Function rename = new Function();
rename.wrkLocTree.CurrentDirectory = StartingPath;
rename.wrkLocTree.GiveUpdatePerFolder();
rename.wrkLocTree.Show();
The second part creates a new class and also should 'create' the window.
public class Function{
public WorkLocationTree wrkLocTree = new();
The third part is for updating the window that won't show up
public void GiveUpdatePerFolder(){
//variable declaration
int dirCounter;
string directoryToAdd = Path.GetFileName(CurrentDirectory);
if(String.IsNullOrEmpty(BeginPath)) BeginPath = MainWindow.StartingPath;
string dirs = Path.GetFileName(BeginPath) + CurrentDirectory.Replace(BeginPath, "");
List<string> directories = dirs.Split('\\').ToList();
dirCounter = directories.Count-1;
// End variable declaration */
if(!oldDirectories.Any()){
if(_textBoxes == null || _textBoxes[0] == null) _textBoxes = new TextBox[1];
_textBoxes[0] = new TextBox{ Text = directoryToAdd, Width = 250 };
AddTextBox(0);
}
else{
if(directories == oldDirectories) return;
if(directories.Count > oldDirectories.Count){
if(_textBoxes == null || _textBoxes[0] == null) _textBoxes = new TextBox[1];
else{
List<TextBox> txtBxConverter = _textBoxes.ToList();
txtBxConverter.Add(new TextBox());
txtBxConverter.Add(new TextBox());
_textBoxes = txtBxConverter.ToArray();
}
_textBoxes[dirCounter] = new TextBox{ Text = directoryToAdd, Width = 100 };
if(_lines == null || _lines[0] == null) _lines = new Line[2];
else{
List<Line> converter = _lines.ToList();
converter.Add(new Line());
converter.Add(new Line());
_lines = converter.ToArray();
}
int lineCounter = _lines.Length > 0 ? _lines.Length : 0;
_lines[lineCounter] = new Line{ VerticalAlignment = VerticalAlignment.Center, X1 = 0, X2 = 7.5, Stroke = Brushes.Chocolate, StrokeThickness = 3 };
_lines[lineCounter + 1] = new Line{ VerticalAlignment = VerticalAlignment.Center, Y1 = -14, Y2 = 1.5, Stroke = Brushes.Chocolate, StrokeThickness = 3 };
AddLine(dirCounter, lineCounter);
AddTextBox(dirCounter);
}
else if(directories.Count < oldDirectories.Count){
ClearLayer(dirCounter, 2);
_textBoxes[directories.Count - 1].Text = directoryToAdd;
AddTextBox(dirCounter);
}
else if(directories.Count == oldDirectories.Count){
if(directories[directories.Count-1] == oldDirectories[directories.Count-1]){
return;
}
ClearLayer(dirCounter, 1);
_textBoxes[dirCounter].Text = directoryToAdd;
AddTextBox(dirCounter);
}
}
oldDirectories.RemoveRange(0, oldDirectories.Count);
for(int i = 0; i < directories.Count; i++){
oldDirectories.Add(directories[i]);
}
InitializeComponent();
}
There's also a small part where the textboxes get added to the Stack panels. But I don't think that it would be necessary to share

Text in richtextbox applying text decorations outside of selection

I have a WPF desktop application that uses MVVM architecture. I started making it following Tim Buchalka's "Windows Presentation Foundation Masterclass" on Udemy (paid course, only mentioning it in case anyone already knows what it's about), specifically the part with making a simple Evernote Clone.
I have a RichTextBox and several buttons that allow the user to change the formatting of the currently selected text - bold, italics, underline and strikethrough. Bold and italics work perfectly fine, the issue is with underline and strikethrough. I can apply either of the properties fine as long as it's the same in the entire selection (all underlined, all strikethrough, both or neither). But when I try to apply the styling to a selection, where one part is udnerlined/strikethrough and the other is not, the formatting gets applied to a text range that is offset compared to the selection itself (not to mention that the styling isn't applied the way I would have like, but the offset is currently the bigger problem). I'll try adding pictures to better illustrate what I mean.
Styling working correctly when the selection is homogenous:
Selected non-homogenous part of text, about to click the underline button:
How the styling gets applied after I clicked the button:
I tried to figure out what's going on using breakpoints, but the method only seems to iterate through the selection, as intended. I'll appreciate any advice and/or constructive criticism. Anyways, here's my code:
Bold button's method:
private void btnUnderline_Click(object sender, RoutedEventArgs e)
{
bool isButtonChecked = (sender as ToggleButton).IsChecked ?? false;
TextDecorationCollection textDecorations = new TextDecorationCollection();
try
{
textDecorations.Add( contentRichTextBox.Selection.GetPropertyValue(
Inline.TextDecorationsProperty) as TextDecorationCollection);
if (isButtonChecked)
{ textDecorations.Add(TextDecorations.Underline); }
else { textDecorations.TryRemove(TextDecorations.Underline, out textDecorations);}
contentRichTextBox.Selection.ApplyPropertyValue(Inline.TextDecorationsProperty,
textDecorations);
}
catch (Exception)
{
textDecorations = new TextDecorationCollection();
if (!contentRichTextBox.Selection.IsEmpty)
{
var tpFirst = contentRichTextBox.Selection.Start;
var tpLast = contentRichTextBox.Selection.End;
var textRange = new TextRange(tpFirst, tpFirst.GetPositionAtOffset(1));
var underlined = (textRange.GetPropertyValue(Inline.TextDecorationsProperty)
as TextDecorationCollection).Contains(TextDecorations.Underline[0]);
for (TextPointer t = tpFirst;
t.CompareTo(tpLast) <= 0;
t = t.GetPositionAtOffset(1))
{
textDecorations.Clear();
textRange = new TextRange(t, t.GetPositionAtOffset(1));
textDecorations = textRange.GetPropertyValue(
Inline.TextDecorationsProperty) as TextDecorationCollection;
if (!underlined)
{ textDecorations.Add(TextDecorations.Underline[0]); }
else { textDecorations.TryRemove(TextDecorations.Underline,
out textDecorations); }
textRange.ApplyPropertyValue(Inline.TextDecorationsProperty,
textDecorations);
}
}
else
{
NewParagraphWhenSelectionIsEmpty();
}
}
}
Strikethrough button's method:
private void btnStrikethrough_Click(object sender, RoutedEventArgs e)
{
bool isButtonChecked = (sender as ToggleButton).IsChecked ?? false;
TextDecorationCollection textDecorations = new TextDecorationCollection();
try
{
textDecorations.Add(contentRichTextBox.Selection.GetPropertyValue(
Inline.TextDecorationsProperty) as TextDecorationCollection);
if (isButtonChecked)
{ textDecorations.Add(TextDecorations.Strikethrough); }
else { textDecorations.TryRemove(TextDecorations.Strikethrough,
out textDecorations); }
contentRichTextBox.Selection.ApplyPropertyValue(Inline.TextDecorationsProperty,
textDecorations);
}
catch (Exception)
{
textDecorations = new TextDecorationCollection();
if (!contentRichTextBox.Selection.IsEmpty)
{
var tpFirst = contentRichTextBox.Selection.Start;
var tpLast = contentRichTextBox.Selection.End;
var textRange = new TextRange(tpFirst, tpFirst.GetPositionAtOffset(1));
var strikedthrough = (textRange.GetPropertyValue(
Inline.TextDecorationsProperty) as
TextDecorationCollection).Contains(TextDecorations.Strikethrough[0]);
for (TextPointer t = tpFirst;
t.CompareTo(tpLast) <= 0;
t = t.GetPositionAtOffset(1))
{
textDecorations.Clear();
textRange = new TextRange(t, t.GetPositionAtOffset(1));
textDecorations = textRange.GetPropertyValue(
Inline.TextDecorationsProperty) as TextDecorationCollection;
if (!strikedthrough)
{ textDecorations.Add(TextDecorations.Strikethrough[0]); }
else { textDecorations.TryRemove(TextDecorations.Strikethrough,
out textDecorations); }
textRange.ApplyPropertyValue(Inline.TextDecorationsProperty,
textDecorations);
}
}
else
{
NewParagraphWhenSelectionIsEmpty();
}
}
}
Method used when selection in the richtextbox changes:
private void contentRichTextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
var selectedWeight = contentRichTextBox.Selection.GetPropertyValue(
FontWeightProperty);
btnBold.IsChecked = (selectedWeight != DependencyProperty.UnsetValue)
&& (selectedWeight.Equals(FontWeights.Bold));
var selectedStyle = contentRichTextBox.Selection.GetPropertyValue(FontStyleProperty);
btnItalics.IsChecked = (selectedStyle != DependencyProperty.UnsetValue)
&& (selectedStyle.Equals(FontStyles.Italic));
var selectedDecoration = contentRichTextBox.Selection.GetPropertyValue(
Inline.TextDecorationsProperty) as TextDecorationCollection;
btnUnderline.IsChecked = (selectedDecoration != null)
&& (selectedDecoration != DependencyProperty.UnsetValue)
&& selectedDecoration.Contains(TextDecorations.Underline[0]);
btnStrikethrough.IsChecked = (selectedDecoration != null)
&& (selectedDecoration != DependencyProperty.UnsetValue)
&& selectedDecoration.Contains(TextDecorations.Strikethrough[0]);
cbEditorFontFamily.SelectedItem = contentRichTextBox.Selection.GetPropertyValue(
Inline.FontFamilyProperty);
if (contentRichTextBox.Selection.GetPropertyValue(Inline.FontSizeProperty)
!= DependencyProperty.UnsetValue)
{ cbEditorFontSize.Text = (contentRichTextBox.Selection.GetPropertyValue(
Inline.FontSizeProperty)).ToString(); }
}
Method used when inserting a new paragraph:
private void NewParagraphWhenSelectionIsEmpty()
{
var fontFamily = new FontFamily(cbEditorFontFamily.SelectedItem.ToString());
var fontSize = Convert.ToDouble(cbEditorFontSize.Text);
var fontStyle = (btnItalics.IsChecked ?? false) ? FontStyles.Italic :
FontStyles.Normal;
var fontWeight = (btnItalics.IsChecked ?? false) ? FontWeights.Bold :
FontWeights.Normal;
var textDecorations = new TextDecorationCollection();
if (btnUnderline.IsChecked ?? false)
{ textDecorations.Add(TextDecorations.Underline[0]); }
if (btnStrikethrough.IsChecked ?? false)
{ textDecorations.Add(TextDecorations.Strikethrough[0]); }
// Check to see if we are at the start of the textbox and nothing has been added yet
if (contentRichTextBox.Selection.Start.Paragraph == null)
{
// Add a new paragraph object to the richtextbox with the fontsize
Paragraph p = new Paragraph();
p.FontFamily = fontFamily;
p.FontSize = fontSize;
p.FontStyle = fontStyle;
p.FontWeight = fontWeight;
p.TextDecorations = textDecorations;
contentRichTextBox.Document.Blocks.Add(p);
}
else
{
// Get current position of cursor
TextPointer curCaret = contentRichTextBox.CaretPosition;
// Get the current block object that the cursor is in
Block curBlock = contentRichTextBox.Document.Blocks.Where
(x => x.ContentStart.CompareTo(curCaret) == -1
&& x.ContentEnd.CompareTo(curCaret) == 1).FirstOrDefault();
if (curBlock != null)
{
Paragraph curParagraph = curBlock as Paragraph;
// Create a new run object with the fontsize, and add it to the current block
Run newRun = new Run();
newRun.FontFamily = fontFamily;
newRun.FontSize = fontSize;
newRun.FontStyle = fontStyle;
newRun.FontWeight = fontWeight;
newRun.Foreground = new
SolidColorBrush((Color)wpfcpEditorFontColour.SelectedColor);
newRun.TextDecorations = textDecorations;
curParagraph.Inlines.Add(newRun);
// Reset the cursor into the new block.
// If we don't do this, the font size will default again when you start
// typing.
contentRichTextBox.CaretPosition = newRun.ElementStart;
}
}
}

How can I check for sliders on a joystick with SharpDX DirectInput?

I'm working on a multi-joystick setup where I need to build custom button mappings. And even map across devices. For example, if there is a separate joystick and throttle quadrant I need to map 'Z' or whatever, over to the throttle input. I also need to be able to check and see if there is a slider(s) available on each stick as I build the mapping profiles, etc. I cannot figure out how to just say something like:
if (joystick.HasSliders)
So far I've tried different variations of
PropertyInfo rxprop = typeof(SharpDX.DirectInput.JoystickState).GetProperty("Sliders");
However, if the joystick does not have sliders, this of course will throw an exception. If it only has a single slider, I will always get back an Int array of Sliders[] with two values, no matter if the stick only has a single slider or not. So it is not a guaranteed way to know if sliders exist, or even how many exist. If there is no second actual slider, the value Sliders[1] is always 0, but if there is a second slider it could still be in the 0 position.
Currently this is what I've been messing with:
usbjoysticks[k].Poll();
JoystickState currentState = null;
try
{
currentState = usbjoysticks[k].GetCurrentState();
//joystickmap.axisRangeMax = usbjoysticks[k].GetObjectInfoById(1);
PropertyInfo rxprop = typeof(SharpDX.DirectInput.JoystickState).GetProperty("Sliders");
var rzvalue = (int[])rxprop.GetValue(currentState, null);
var mySlider1 = rzvalue[0];
var datas = usbjoysticks[k].GetBufferedData();
foreach (var state in datas)
{
Console.WriteLine(state);
if (state.Offset == JoystickOffset.X)
{
Console.WriteLine(state.Value);
}
}
//DeviceObjectInstance my = usbjoysticks[k].GetObjectInfoByName("Sliders1");
var stuff = usbjoysticks[k].GetObjectPropertiesByName("Sliders0");
//=================
joystickmap.jX = "X";
joystickmap.axisRangeMax = usbjoysticks[k].GetObjectPropertiesByName("Y").Range.Maximum; //65535
joystickmap.jY = "Y";
if (currentState.Z != 0)
{
joystickmap.jZ = "Z";
var maxZrange = usbjoysticks[k].GetObjectPropertiesByName("Z").Range.Maximum;
joystickmap.axisRangeMax = usbjoysticks[k].GetObjectPropertiesByName("Z").Range.Maximum;
}
if (currentState.Sliders[0] != 0 || currentState.Sliders[1] != 0) //TODO possible change to Joystick State value in class object instead of text.
{
joystickmap.SLD1 = "Slider1";
//joystickmap.jZ = "Sliders";
joystickmap.jsSliders = currentState.Sliders;
var maxSld1range = usbjoysticks[k].GetObjectPropertiesByName("Sliders0").Range.Maximum;
joystickmap.sld1 = joystickmap.jsSliders[0];
joystickmap.sld2 = joystickmap.jsSliders[1];
}
if (currentState.Sliders[1] != 0)
{
joystickmap.SLD2 = "Slider2";
}
if (currentState.RotationX != 0)
{
joystickmap.rX = "RotationX";
}
if (currentState.RotationY != 0)
{
joystickmap.rY = "RotationY";
}
if (currentState.RotationZ != 0)
{
joystickmap.rZ = "RotationZ";
//joystickmap.jZ = "RotationZ";
}
joystickmap.axisdivider = 2;
for (var b = 0; b < 20; b++)
{
//joystickmap.joybuttons.Add(currentState.Buttons[b]);
joystickmap.joybuttons[b] = (b + 1);
}
joystickmappings.Add(joystickmap);
if (!File.Exists(filename))
{
File.WriteAllText(filename, JsonConvert.SerializeObject(joystickmap));
// serialize JSON directly to a file
using (StreamWriter file = File.CreateText(filename))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, joystickmap);
}
}
}
catch (Exception e)
{
MessageBox.Show("USB joystick map creation failure!\n" + e.Message);
break;
}

How to play media element synchronously?

I have a datatemplate in which i have a text block and speech synthesizer. Whwn i bind it with data the template spawns atleast 3 children. A speech synthesizer is activated on click of one checkbox. It works fine in normal conditions. But if i test it vigorously and try to play more than one synthesizer before initialization, it plays unexpected audio. And it continue even after exiting from that page.
I am sharing code for check box click event. Please suggest a solution.
private async void checkboxPlay_Click(object sender, RoutedEventArgs e)
{
// when _mediaCounter == 0, synthesizer is stopped or not played
// when _mediaCounter == 1, it is playing
// when _mediaVounter == 2, it is paused
Grid gd = (Grid)((sender as CheckBox).Parent as Grid).Parent;
var child = VisualTreeHelper.GetParent(gd);
try
{
if (sender is CheckBox)
{
if (_listElement.Count > 0)
{
if (sender != _listElement[_checkCounter].CheckBox && _listElement[_checkCounter].CheckBox != null)
{
_listElement[_checkCounter].MediaElement.Stop();
_mediaCounter = 0;
_timer.Stop();
_listElement[_checkCounter].Slider.Value = 0;
_description = string.Empty;
_listElement[_checkCounter].CheckBox.IsChecked = false;
}
}
CheckBox cb = sender as CheckBox;
Grid x = (Grid)VisualTreeHelper.GetParent(cb);
_mediaIndex = Convert.ToInt32(
x.DataContext.ToString().Substring(x.DataContext.ToString().Length - 1, 1)
) - 1;
_checkCounter = _mediaIndex;
if (_description != cb.DataContext.ToString())
{
cb.IsChecked = true;
_description = cb.DataContext.ToString();
_mediaCounter = 0;
_InitializeCheckbox(cb);
_InitializeMedia();
}
}
if (_mediaCounter == 0)
{
_mediaCounter = 1;
string desc = string.Empty;
SpeechSynthesizer synth = new SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(_description.ToString());
_listElement[_checkCounter].MediaElement.SetSource(stream, stream.ContentType);
_listElement[_checkCounter].MediaElement.Play();
}
else if (_mediaCounter == 1)
{
_listElement[_checkCounter].MediaElement.Pause();
_timer.Stop();
_mediaCounter = 2;
}
else
{
_listElement[_checkCounter].MediaElement.Play();
_timer.Start();
_mediaCounter = 1;
}
}
catch
{
}
}
Have you tried using the MediaElement.CurrentState property?
MediaElement.CurrentState
here's a link
http://msdn.microsoft.com/En-US/Library/Windows/Apps/windows.ui.xaml.controls.mediaelement.currentstate

Problem with updating ListBox control in WPF

I have an application which has to monitor 211 rods, and every 5 seconds it will update 2 ListBox controls, each one containing either the inserted rods or the removed ones. When I manually use the button for inserting/removing rods the code executes perfectly and the ListBoxes update properly. When I use the global button which inserts all 211 one of the ListBox controls stops working properly.
The code for ListBox update
bool IClear = true, RClear = true;
for (int foo = 0; foo < Rods.Count; foo++)
{
if (Rods[foo].State == RodState.Inserted)
{
UpdateRodList update = new UpdateRodList(UpdateIRodUI);
if (IClear)
{
InsertedRods.Dispatcher.BeginInvoke(update, System.Windows.Threading.DispatcherPriority.Normal, foo, true);
IClear = false;
}
else
{
InsertedRods.Dispatcher.BeginInvoke(update, System.Windows.Threading.DispatcherPriority.Normal, foo, false);
}
}
if (Rods[foo].State == RodState.Removed)
{
UpdateRodList update = new UpdateRodList(UpdateRRodUI);
if (RClear)
{
RemovedRods.Dispatcher.BeginInvoke(update, System.Windows.Threading.DispatcherPriority.Normal, foo, true);
RClear = false;
}
else
{
RemovedRods.Dispatcher.BeginInvoke(update, System.Windows.Threading.DispatcherPriority.Normal, foo, false);
}
}
}
The code for the insert button (the remove one is similar)
Int32[] RodsID = null;
bool bParsed = false;
if (RemovingRods_.Text.Contains("*"))
{
RodsID = new Int32[211];
for (int i = 0; i < 211; i++)
{
RodsID[i] = i;
}
RemovingRods_.Text = "";
bParsed = true;
}
if (RemovingRods_.Text.Contains("-"))
{
string stext = RemovingRods_.Text;
Int32 a = Int32.Parse(RemovingRods_.Text.Substring(0, RemovingRods_.Text.IndexOf("-")));
Int32 b = Int32.Parse(RemovingRods_.Text.Substring(RemovingRods_.Text.IndexOf("-") + 1));
RodsID = new Int32[b - a];
for (int i = 0; i < b - a; i++)
{
RodsID[i] = i + a;
}
RemovingRods_.Text = "";
bParsed = true;
}
if (!bParsed)
{
string[] RodsID_;
char[] split = { ' ' };
RodsID_ = RemovingRods_.Text.Split(split);
RemovingRods_.Text = "";
RodsID = new Int32[RodsID_.Length];
for (int i = 0; i < RodsID_.Length; i++)
{
RodsID[i] = Int32.Parse(RodsID_[i]);
}
}
foreach (int numb in RodsID)
{
if (Rods[numb].Type == "Control Rod")
{
ControlRod Rod = new ControlRod();
Rod.Number = numb;
Rod.RodState = RodState.Changing;
RemovingCRods.Add(Rod);
}
if (Rods[numb].Type == "Shortened Control Rod")
{
ShortenedControlRod Rod = new ShortenedControlRod();
Rod.Number = numb;
Rod.RodState = RodState.Changing;
RemovingSRods.Add(Rod);
}
if (Rods[numb].Type == "Automated Control Rod")
{
// Automated Rods -- NO MANUAL CONTROL
}
}
And the global button code
try
{
Int32[] RodsID = null;
string text = "0-211";
RodsID = new Int32[211];
for (int i = 0; i < 211; i++)
{
RodsID[i] = i;
}
foreach (int numb in RodsID)
{
if (Rods[numb].Type == "Control Rod")
{
ControlRod Rod = new ControlRod();
Rod.Number = numb;
Rod.RodState = RodState.Changing;
InsertingCRods.Add(Rod);
}
if (Rods[numb].Type == "Shortened Control Rod")
{
ShortenedControlRod Rod = new ShortenedControlRod();
Rod.Number = numb;
Rod.RodState = RodState.Changing;
InsertingSRods.Add(Rod);
}
if (Rods[numb].Type == "Automated Control Rod")
{
AutomatedControlRod Rod = new AutomatedControlRod();
Rod.Number = numb;
Rod.RodState = RodState.Changing;
InsertingARods.Add(Rod);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
What happens is when I press the global one, the Removed Rods ListBox will have all the rods as it should, and the Inserted Rods ListBox will contain the rods that were inserted before I pressed the button. It's as if when I pressed this button, this control doesn't update. P.S. If I remove rods manually using the button or insert it works perfectly.
As for the code requested by Marko:
private void UpdateIRodUI(Int32 foo, Boolean clear)
{
if (clear)
{
InsertedRods.Items.Clear();
}
InsertedRods.Items.Add(Rods[foo].Number + " : " + Rods[foo].Type + " (" + foo.ToString() + ")");
}
private void UpdateRRodUI(Int32 foo, Boolean clear)
{
if (clear)
{
RemovedRods.Items.Clear();
}
RemovedRods.Items.Add(Rods[foo].Number + " : " + Rods[foo].Type + " (" + foo.ToString() + ")");
}
Update: I have put the update ListBox code in a seperate function and took Marko's advice and also put in a function the InsertRods. Everything works fine now, but it seems that after I press the "emergency" button the InsertedRods ListBox updates and works just fine but RemovedRods just stops updating, unless I do it manually (it's supposed to update every 5 seconds through a Tick event). I even tried inserting all the rods, updating the ListBoxes and the clearing the "faulty" ListBox and still nothing, same result.
I just took a quick glance of your posted code without focusing very deeply on it and a couple of questions popped into mind:
1) You posted your code for ListBox update, but it's unclear from the other two code pieces that where do you call the ListBox update method?
2) The code that you posted for "insert button" looks more like the code from the "remove button", because of Removing_Rods.Add()... But why do you duplicate your insert/remove button code in your global button code? Why not have an insert method, that both the insert button and global (insert) button call? And the same for remove. If you need to slightly alter the code based on whether the caller is the insert button or the global button, you can pass in a variable and check it inside the insert method.
3) Have you tried debugging your code? As in whether the listbox update method is called when the global button code is executed...

Categories

Resources