프로그래밍 방식으로 버튼 추가 - 마우스 이벤트 구독 문제
-
05-07-2019 - |
문제
코드에 버튼 목록을 추가하고 Mouseleave 이벤트에도 구독합니다. 각 버튼마다 익명의 함수로 이벤트를 서브하여 문제는 앱을 실행할 때 모두 마지막 익명 기능에 가입된다는 것입니다. 여기에 코드가 있습니다. 나는 나 자신을 설명하기를 바랍니다.
var modules = ModulesSC.GetAllMoudules();
var imageSet = ModulesSC.GetModuleImageSet();
foreach (var module in modules)
{
var btn = new Button();
btn.SetResourceReference(Control.TemplateProperty, "SideMenuButton");
btn.Content = module.Title;
btn.MouseEnter += (s, e) => { ShowInfo(module.Description); };
btn.MouseLeave += (s, e) => { HideInfo(); };
ModuleButtons.Children.Add(btn);
}
protected void HideInfo()
{
DescriptionLabel.Visibility = Visibility.Collapsed;
DescriptionText.Text = string.Empty;
}
protected void ShowInfo(string description)
{
DescriptionLabel.Visibility = Visibility.Visible;
DescriptionText.Text = description;
}
앱을 실행하면 모두 las "module.description"으로 showinfo를 호출합니다.
감사합니다 -alejandro
해결책
이것은 C#이 루프 변수를 초과하는 방식과 관련된 문제입니다. 임시 변수를 추가하십시오 내부에 익명 방법으로 사용하십시오.
foreach (var module in modules)
{
var theModule = module; // local variable
var btn = new Button();
btn.SetResourceReference(Control.TemplateProperty, "SideMenuButton");
btn.Content = theModule.Title; // *** use local variable
btn.MouseEnter += (s, e) => { ShowInfo(theModule.Description); }; // *** use local variable
btn.MouseLeave += (s, e) => { HideInfo(); };
ModuleButtons.Children.Add(btn);
}
루프 변수 "모듈"대신 로컬 변수 "테마"를 사용하십시오.
다른 팁
나는 이것이 어떤 언어인지는 모르겠지만 C#일 수 있습니다.
버튼 클릭 이벤트 처리기는 "객체 발신자"와 eventArgs 인수가 기능에 있어야합니다.
"객체 발신자"는 어떤 버튼을 누르는 지 알 수 있습니다.
Button pressedButton = (Button)sender;
if(pressedButton.Text.Equals("Button 1")
doStuff();
예를 들어, 텍스트 필드를 비교하는 것보다 어떤 버튼을 결정하는 더 좋은 방법이 있지만, 아이디어를 얻을 수 있습니다.
제휴하지 않습니다 StackOverflow