Compiler error when creating IntegerUpDown ValueChanged event - c#

I'm using the IntegerUpDown control from WPFExtendedToolkit
However, I'm unable to assign the event my function so that when the value is changed it will call my function. I'm pretty new to both c# and wpf so help is greatly appreciated. I've been trying to get it to work as show in a similar example here.
private IntegerUpDown m_argumentUpDown;
public IntArgumentOption(ArgumentOptionDescription argumentDesc) : base(argumentDesc)
{
m_argumentUpDown = new IntegerUpDown
{
Watermark = argumentDesc.m_watermark,
Increment = (int)argumentDesc.m_interval,
Minimum = (int)argumentDesc.m_minimum,
Maximum = (int)argumentDesc.m_maximum,
FormatString = "G",
SelectAllOnGotFocus = true,
MinWidth = 50,
FontSize = 10,
Margin = new System.Windows.Thickness(5, 0, 0, 0),
};
// COMPILER ERROR:
m_argumentUpDown.ValueChanged += new RoutedPropertyChangedEventHandler<int>(ArgumentChanged);
}
void ArgumentChanged(object sender, RoutedPropertyChangedEventArgs<int> e)
{
}
Doing this results in the compiler error:
error CS0029: Cannot implicitly convert type 'System.Windows.RoutedPropertyChangedEventHandler< int >' to 'System.Windows.RoutedPropertyChangedEventHandler< object >'

Here in the UpDownBase class (Xceed.wpfToolkit.dll) the method signature for ValueChanged is:
public event RoutedPropertyChangedEventHandler<object> ValueChanged;
hence in your code you have to declare a event handler where the generic is of type "Object" instead of int. Because of the mismatch in type the compiler is unable to implicitly convert to Int from object.
So change code as below
m_argumentUpDown.ValueChanged += new RoutedPropertyChangedEventHandler<object>(ArgumentChanged);
}
void ArgumentChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
//type caste e.newValue and e.OldValue
}

The following will work, I tested that. But I dont know if this is considered work around or creator of IntegerUpDown control meant it to be used this way.
m_argumentUpDown.ValueChanged += new RoutedPropertyChangedEventHandler<object>(ArgumentChanged);
//or you can change above line to following for brevity. ReSharper always suggesting me to do this
//m_argumentUpDown.ValueChanged += ArgumentChanged;
void ArgumentChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
//you need to cast New and Old value to int since both are of type object now
int newVal = (int)e.NewValue;
int oldVal = (int)e.OldValue;
}

Related

Add Click event to my dynamically created Xaml Button

I'm currently writing a function that creates button in XAML (on runtime) according to JSON information that is received from an API call in C#.
I currently have the following code:
Button downloadButton = new Button();
downloadButton.Click += new RoutedEventHandler(DownloadContent);
But I get the following error:
An object reference is required for the non-static field, method, or
property 'Mainwindow.DownloadContent(object, RoutedEventArgs)'
I've tried changing it to downloadButton.Click += new RoutedEventHandler(this, DownloadContent); but that gives me the error:
Keyword 'this' is not valid in a static property, static method, or static field initializer
For reference this is what DownloadContent looks like
private void DownloadContent(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("API-URL"), contentZip);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(InstallContent);
}
This is what I want the button to look like (skipping the other stuff like background color, etc.)
<Button Name="Downloadbutton"
Content="Download"
Click="DownloadContent"
</Button>
Am I missing something as why I get this Error and how could I fix it?
EDIT
The Installcontent function looks like this:
private void InstallContent(object sender, AsyncCompletedEventArgs e)
{
ZipFile.ExtractToDirectory(contentZip, contentPath, true);
File.Delete(contentZip);
writeJsonData(DLCbuttonTag);
Downloadbutton.Visibility = Visibility.Collapsed;
Uninstallbutton.Visibility = Visibility.Visible;
}
The function that creates the button:
public static void getContentList()
{
string jsonString = File.ReadAllText(#"C:\Users\stage\OneDrive\Documenten\ContentInfo.json")
ContentList contentList = JsonConvert.DeserializeObject<ContentList>(jsonString);;
for (int i = 0; i < contentList.Content.Count; i++)
{
StackPanel dynamicStackPanel = new StackPanel();
dynamicStackPanel.Orientation = Orientation.Horizontal;
dynamicStackPanel.Background = Brushes.Transparent;
Button downloadButton = new Button();
downloadButton.Click += new RoutedEventHandler(DownloadContent);
dynamicStackPanel.Children.Add(downloadButton);
}
}
The problem is that getContentList is declared as static. You try to reference the method DownloadContent which is an instance method. Remove the static from getContentList to fix the error.
The reason for the error is that static methods cannot access instance members. Static members do not run in the context of a particular instance, but in the context of the type itself. While in the case of WPF there most likely is no other instance of your page, in theory there could be many. The static method would not know which instance to pick, hence the error.
See this link for details on static members.
As a sidenote: in C#, methods are usually started with a capital letter (Pascal casing) regardless of their access modifier. So getContentList would be GetContentList.

How to build a TimePicker.TimeChanged Event in c#?

in my tool I create a TimePicker XAML control while runtime, but I'm struggling with the TimeChanged Event.
// TimePicker
TimePicker timePicker = new TimePicker
{
Margin = new Thickness(0, 0, 0, 7),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Bottom,
RequestedTheme = ElementTheme.Dark,
Name = "Schedule_" + lightnumber + "_timepicker",
ClockIdentifier = "24HourClock",
Time = TimeSpan.Parse(hue_schedules_localtime),
};
hueGrid.Children.Add(timePicker);
timePicker.TimeChanged += new TimePickerValueChangedEventArgs(Schedule_TimeChange);
private void Schedule_TimeChange(string sender, TimePickerValueChangedEventArgs e)
{
}
I always get this error message "Error CS1729 'TimePickerValueChangedEventArgs' does not contain a constructor that takes 1 arguments"
Unfortunately I didn't found an c# example on the internet.
Can somebody please help me with this problem.
You have a mistake in subscribing event code, you should add method/local function/lambda as subscriber, while you're trying to add TimePickerValueChangedEventArgs instance as subscriber instead, and TimePickerValueChangedEventArgs constructor doesn't accept one parameter, so that's why you got TimePickerValueChangedEventArgs does not contain a constructor that takes 1 arguments error. Fixed code:
timePicker.TimeChanged += Schedule_TimeChange;
private void Schedule_TimeChange(object sender, TimePickerValueChangedEventArgs e)
{
}

Cannot implicitly convert type System.EventHandler to System.EventHandler<object> error

I am trying to implement a Timer in windows phone app.It works fine in Windows Phone App(Silverlight) but it isnt working in Windows Phone Blank App.But it gives me following error-
Cannot implicitly convert type System.EventHandler to System.EventHandler<object>
This is my code -
namespace Timer
{
public partial class MainPage : Page
{
DispatcherTimer mytimer = new DispatcherTimer();
int currentcount = 0;
public MainPage()
{
InitializeComponent();
mytimer = new DispatcherTimer();
mytimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
mytimer.Tick += new EventHandler(mytime_Tick);
//HERE error comes Cannot implicitly convert type System.EventHandler to System.EventHandler<object>
}
private void mytime_Tick(object sender,EventArgs e)
{
timedisplayBlock.Text = currentcount++.ToString();
}
private void startButton_Click(object sender, RoutedEventArgs e)
{
mytimer.Start();
}
}
}
I tried Cannot implicitly convert type 'System.EventHandler' to 'System.EventHandler<object>' for storyboard complete
But it even helped.How can I fix this error?
Referencing the method handler for the event directly will infer the type, satisfying the generic type declaration requirement.
mytimer.Tick += mytime_Tick;
Alternatively, explicitly declaring the generic type and using the generic EventHandler constructor,
mytimer.Tick += new EventHandler<object>(mytime_Tick);
would do the trick.
In addition, according to the documentation, your handler has the wrong signature. It should be:
private void mytime_Tick(object sender,object e)
{
timedisplayBlock.Text = currentcount++.ToString();
}
Just write mytimer.Tick += then press TAB Key two times it will fix your bug.
If you want to avoid a conversion, you can always do the following:
mytimer.Tick += (s, ev) => { mytime_Tick(s, ev); }
It's very useful if you are validating nullables:
mytimer.Tick += (s, ev) => { mytime_Tick?.Invoke(s, ev); }
Regards, Nicholls
As the error message is trying to tell you, you need to create an EventHandler<object>.
Or, better yet, leave the delegate type out entirely and just add the method name.

How to convert a constructor type to 'System.Windows.UIElement' (blockUIContainer)?

I created a class and I want to use the constructor of the class Rtb(),
public class Rtb
{
public RichTextBox newRTB;
public Rtb()
{
newRTB = new RichTextBox();
newRTB.IsReadOnly = true;
newRTB.MouseDoubleClick += new MouseButtonEventHandler(newRTB_MouseDoubleClick);
}
private void newRTB_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
.....
}
}
In below code, i created an object of Rtb(),but this object can not assigned to newBUC.Child, an error after run: Cannot implicitly convert type 'WpfApplication1.Rtb' to 'System.Windows.UIElement'
private void menu_Click(object sender, RoutedEventArgs e)
{
BlockUIContainer newBUC = new BlockUIContainer();
newBUC.Margin = new Thickness(50, 10, 50, 10);
mainMenu.Document.Blocks.Add(newBUC);
Rtb newnew = new Rtb();
newBUC.Child = newnew;
}
I tried to use to cast it, and use "as", like below, but it did not work. I think probably i need the right type to perform the assignment, how should i do?
newBUC.Child = newnew as BlockUIContainer;
newBUC.Child = (BlockUIContainer) newnew;
You can't add newnew as a Child, because you class does not inherit from UIElement. But what can you do is set Child to underlying RichTextBox called newRTB which inherits from UIElement
newBUC.Child = newnew.newRTB;
In my case I was missing a reference to PresentationFramework.dll
located on Program files* x86( reference assembles„Microsoft\FRamewrk\3.0\
or your FRamework version
This got me access to all dependencies on my XAML Partial class and therefore able to resolve
I hope this also can help on your coding, It worked for me.

add data item to observablecollection?

I need to add selected items to this collection..
I select my item on a page and then appbar appears and i want on the appbar button tapped event to add item to collection that will be displayed on the other page..
private void Button_Tapped_1(object sender, TappedRoutedEventArgs e)
{
AllActors m = new AllActors();
ActorsObject objkt = itemGridView.SelectedItem;
m.allActors.Add(objkt);
}
this doesnt work... here are my classes:
public class AllActors : LivingDataCommon
{
public AllActors()
: base(String.Empty, String.Empty)
{
}
public AllActors(String ID, String title)
: base(ID, title)
{ }
private ObservableCollection<ActorsObject> _AllActors = new ObservableCollection<ActorsObject>();
public ObservableCollection<ActorsObject> allActors
{
get { return this._AllActors; }
}
}
Problem one: compiler error "Cannot implicitly convert type"
ActorsObject objkt = itemGridView.SelectedItem;
The GridView's SelectedItem property returns an object. You're trying to assign that to a variable of type ActorsObject, and the compiler can't assume that this is okay. You have to tell it...
ActorsObject objkt = (ActorsObject)itemGridView.SelectedItem;
The compiler's error message specifically asked "are you missing a cast?" and pointed to this line. That's useful information - it's just told you what was wrong and suggested how to fix it. Always read compiler errors and think about what they're telling you, don't just reduce it to "it doesn't work".
Problem two: "it doesn't do what I want"
private void Button_Tapped_1(object sender, TappedRoutedEventArgs e)
{
AllActors m = new AllActors();
ActorsObject objkt = itemGridView.SelectedItem;
m.allActors.Add(objkt);
}
Read this carefully and think about what it's doing. On the first line of the function, you're creating a new AllActors object and assign it to 'm'. On the third line, you make a change to that object. But then your function ends, and you've thrown that object away!
It's more likely that to achieve what you want you need to create the AllActors object as a field on your window class. Then you can keep the object around, bind to it, and any changes to it will be kept. Something like this, although you will also need some UI to display this data.
private AllActors _m = new AllActors();
private void Button_Tapped_1(object sender, TappedRoutedEventArgs e)
{
ActorsObject objkt = (ActorsObject)itemGridView.SelectedItem;
_m.allActors.Add(objkt);
}
You need to change
ActorsObject objkt = itemGridView.SelectedItem;
to
ActorsObject objkt = (ActorsObject)itemGridView.SelectedItem;
you are missing a cast there.
Try this:
ActorsObject objkt = (ActorsObject ) itemGridView.SelectedItem;
m.allActors.Add(objkt);
or
ActorsObject objkt = itemGridView.SelectedItem as ActorsObject;
m.allActors.Add(objkt);
You have to cast SelectedItem, since it is object not ActorsObject

Categories