c# - How to bind a command to a button -
i new wpf , fancy binding stuff, followed these tutorial , got xaml:
<button x:name="btn" content="refresh" command="{binding refreshcmd}" /> and code:
public someclass () { initializecomponent(); createrefreshcmd(); btn.datacontext=this; // without line not work !! } public icommand refreshcmd { get; internal set; } private bool canexecuterefreshcmd () { homecoming true; } private void createrefreshcmd () { refreshcmd=new relaycommand(e => refreshexec(), c => this.canexecuterefreshcmd()); } public void refreshexec () { // fancy here ! } but without lastly line in constructor not work.
in tutorial line not exist.
how can avoid this?
edit:
i clicked databinding visual studio , got this:
command="{binding refreshcmd, mode=oneway, relativesource={relativesource findancestor, ancestortype={x:type my:spielerei}}}" is necessary?
for binding work, need set info context bindings target, yes, necessary. in command binding posted in edit, binding instructed refreshcmd property on ancestor of button command of type my:spielerei, assume containing window type. why explicit setting of datacontext doesn't appear in tutorial.
bindings , commands can used in code-behind, much more commonly used view-models in mvvm pattern. involves setting datacontext of class view-model, contains properties , commands want bind to. alter code follow mvvm, need view-model:
public class someclassviewmodel { public someclassviewmodel() { this.refreshcmd = new relaycommand(e => refreshexec(), c => this.canexecuterefreshcmd()); } public icommand refreshcmd { get; internal set; } private bool canexecuterefreshcmd() { homecoming true; } public void refreshexec() { // fancy here ! } } then, in code-behind, create view-model, , assign info context of object:
public class someclass { public someclass() { initializecomponent(); this.datacontext = new someclassviewmodel(); } } notice of code someclass code-behind file has moved view-model - testable, , xaml controls can communicate view-model binding properties , executing commands.
c# wpf xaml
No comments:
Post a Comment