应用程序运行后运行命令

时间:2014-12-27 18:22:49

标签: c# xaml windows-phone-8

我注意到它不仅发生在一个项目中,而且发生在多个项目上,所以我将提供简单的示例。我有这样的xaml:

<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 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) => { });
        }
    }
}

和主页:

    public MainPage()
    {
        this.InitializeComponent();

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

这很奇怪,但PressedButton只在应用程序启动时运行(它在启动时运行的奇怪吗?)。之后,即使按下按钮后也没有触发任何内容。我无法弄清楚出了什么问题。

1 个答案:

答案 0 :(得分:1)

我认为你可能会在每次&#34; getter&#34;返回一个新命令时引起绑定问题。叫做。尝试在构造函数中设置一次命令(例如)。

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
}