I have the code that change the state of boolean property on mouseclick, depending on name of the clicked object:
private void Grid开发者_StackOverflow中文版_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement feSource = e.Source as FrameworkElement;
switch (feSource.Name)
{
case "r1s1":
if (r1s1.IsSelected == false)
r1s1.IsSelected = true;
else
r1s1.IsSelected = false;
break;
case "r1s2":
if (r1s2.IsSelected == false)
r1s2.IsSelected = true;
else
r1s2.IsSelected = false;
break;
.............
}
e.Handled = true;
}
I would like to do the same action passing the name of the sender (r1s1, r1s2,..and so on) as a parameter to function where this string combines with a name of property (IsSelected) just to optimize code. Something like that (just idea):
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement feSource = e.Source as FrameworkElement;
ChangeSelection (feSource.Name)
}
public void ChangeSelection(string name)
{
if (name.IsSelected == false)
name.IsSelected = true;
else
name.IsSelected = false;
}
Please, correct me. What I am doing wrong?
I'm not awesomes at WPF but I believe you want to pass feSource into ChangeSelection instead. Then cast it to it's "real" type, be this CheckBox or whatever and then modify the .IsSelected property on it.
I have no idea why you would want to do this by name when you get the real object as the parameter (object sender).
You might just want to store the target reference in the "tag" property of each item. Then you won't have all the magic strings to pass around.
You want to access a control by its name. Following code assumes your control is a "RadioButton" and your code is on a form.
public void ChangeSelection(string name)
{
if (this.Controls.ContainsKey(name))
{
RadioButton radio1 = this.Controls[name] as RadioButton;
radio1.IsSelected = !radio1.IsSelected;
}
}
What you're passing to your function is a string. So when you're attempting to address name.IsSelected in your function, you're looking for the String.IsSelected method (does one exist?)
Where you declare r1s1 and r1s3 in your top function? Those are the objects you should be trying to call .IsSelected on.
And a syntax sugar comment:
public void ChangeSelection(string name)
{
// resolve object from name here
feObject.IsSelected = ! feObject.IsSelected;
}
精彩评论