1

遵循 MVVM 模式。每次 TextBox 中的 Text 更改时,我都需要 TextBox 来触发 viewModel 上的属性设置器。问题是 ViewModel 上的 setter 永远不会被调用。这就是我所拥有的:

查看 (.cs)

public partial class AddShowView : PhoneApplicationPage
{
    public AddShowView()
    {
        InitializeComponent();
    }

    private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
    {
        DataContext = new AddShowViewModel(this.NavigationService);
    }

    private void SearchTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
    {
        var textBox = (TextBox)sender;
        var binding = textBox.GetBindingExpression(TextBox.TextProperty);
        binding.UpdateSource();
    }
}

查看 (.xaml),仅相关部分

<TextBox Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="{Binding SearchText, UpdateSourceTrigger=Explicit}" TextChanged="SearchTextBox_TextChanged_1" />

视图模型

public class AddShowViewModel : PageViewModel
{
    #region Commands

    public RelayCommand SearchCommand { get; private set; }

    #endregion

    #region Public Properties

    private string searchText = string.Empty;
    public string SearchText
    {
        get { return searchText; }
        set
        {
            searchText = value;
            SearchCommand.RaiseCanExecuteChanged();
        }
    }

    #endregion

    public AddShowViewModel(NavigationService navigation) : base(navigation)
    {
        SearchCommand = new RelayCommand(() => MessageBox.Show("Clicked!"), () => !string.IsNullOrEmpty(SearchText));
    }
}

从源到目标的绑定有效,我已经仔细检查过,所以 DataContext 设置正确。我不知道我哪里出错了。感谢您的帮助。

4

1 回答 1

1

您需要将绑定模式设置为 TwoWay,否则它只会从您的 ViewModel 中读取值,而不是更新它。

Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=Explicit}"
于 2012-10-31T20:01:36.507 回答