【问题标题】:Binding source not updating绑定源不更新
【发布时间】:2012-10-31 19:55:13
【问题描述】:

遵循 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 设置正确。我不知道我哪里出错了。 感谢您的帮助。

【问题讨论】:

    标签: c# mvvm windows-phone windows-phone-8


    【解决方案1】:

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

    Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=Explicit}"
    

    【讨论】:

    • 谢谢,我以为这是默认设置。
    • 这是 WPF 的默认设置,而不是 Silverlight 和 Windows Phone。
    • 你也应该在 SearchText 属性的设置器中调用NotifyPropertyChanged("SearchText");
    • 仅当他希望将其更新回 UI 时。我不明白为什么这种情况必然如此。
    猜你喜欢
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2011-06-08
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    相关资源
    最近更新 更多