2014-12-27 5 views
1

하나의 프로젝트뿐만 아니라 여러 프로젝트에서도 문제가 발생한다는 것을 알았습니다. 따라서 간단한 예제를 제공 할 것입니다.응용 프로그램 실행 후 명령 실행

public abstract class ObservableObject : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
     { 
      var e = new PropertyChangedEventArgs(propertyName); 
      this.PropertyChanged(this, e); 
     } 
    } 
} 

public class Command : ICommand 
{ 
    private Action<object> action; 

    public Command(Action<object> action) 
    { 
     this.action = action; 
    } 

    public bool CanExecute(object parameter) 
    { 
     if (action != null) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

    public event EventHandler CanExecuteChanged; 

    public void Execute(object parameter) 
    { 
     if (action != null) 
     { 
      action((string)parameter); 
     } 
    } 
} 

public class TestViewModel : ObservableObject 
{ 
    public ICommand PressedButton 
    { 
     get 
     { 
      return new Command((param) => { }); 
     } 
    } 
} 

메인 페이지 : 데이터 바인딩에

<Page 
x:Class="TestApp.MainPage" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:TestApp" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d" 
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 

<Grid> 
    <Button Content="Button" Command="{Binding PressedButton}" HorizontalAlignment="Left" Margin="0,-10,0,-9" VerticalAlignment="Top" Height="659" Width="400"/> 
</Grid> 
</Page> 

내 수업 :

public MainPage() 
    { 
     this.InitializeComponent(); 

     this.NavigationCacheMode = NavigationCacheMode.Required; 
     DataContext = new TestViewModel(); 
    } 

그것은 이상한하지만 PressedButton는 응용 프로그램 시작에서 실행 (ISN '나는 그런 XAML있어 그 이상한 시작 그것은 실행?). 그 후에도 버튼을 클릭 한 후에도 아무 것도 트리거되지 않습니다. 나는 무엇이 잘못되었는지 알 수 없다.

답변

1

"getter"가 호출 될 때마다 새로운 명령을 반환하여 바인딩 문제가 발생할 수 있다고 생각합니다. 생성자에서 명령을 한 번 설정해보십시오 (예 :). 그들

public MainPage() 
{ 
    PressedAdd = new Command(param => SaveNote()); 
} 

public ICommand PressedAdd { get; private set; } 

SaveNote() 방법에서는 값을 테스트 할 수 있으며, 중 (저장 여부) 저장 :

private void SaveNote() 
{ 
    if (NoteTitle == null || NoteContent == null) 
     return; 

    // Do something with NoteTitle and NoteContent 
} 
관련 문제