如何从视图模型中更新对DataContext的绑定?

时间:2017-07-28 13:01:27

标签: c# wpf mvvm binding ivalueconverter

我有约束力:

<TextBlock Text="{Binding Converter={local:Converter}}" />

带转换器:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var vm = (ViewModel)value;
    return vm.SomeProperty;
}

更改SomeProperty不会更新屏幕上的值。转换器没有被调用。

如何从视图模型中更新此类绑定?

注意:在实际项目中,转换器将用于执行一些计算和返回结果。实际上它甚至会MultiBinding与不同的视图模型具有类似的绑定。我遇到了问题,并且能够将案例缩小到一个简单的Binding,其中绑定不用于绑定到属性,但是像这样。

MCVE xaml:

<StackPanel>
    <TextBlock Text="{Binding Converter={local:Converter}}" />
    <Button Content="..." Click="Button_Click" />
</StackPanel>

和代码:

public partial class MainWindow : Window
{
    ViewModel _vm = new ViewModel();

    public MainWindow()
    {
        InitializeComponent();
        DataContext = _vm;
    }

    void Button_Click(object sender, RoutedEventArgs e) => _vm.SomeProperty += "b";
}

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string property) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));

    string _someProperty = "a";
    public string SomeProperty
    {
        get { return _someProperty; }
        set
        {
            _someProperty = value;
            OnPropertyChanged(nameof(SomeProperty));
        }
    }
}

public class Converter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider) => this;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var vm = (ViewModel)value;
        return vm.SomeProperty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

1 个答案:

答案 0 :(得分:0)

如果@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() .dataSource(dataSource) .rolePrefix("ROLE_") .passwordEncoder(passwordEncoder()) .usersByUsernameQuery("SELECT username, password, enabled FROM app_user WHERE username = ?") .authoritiesByUsernameQuery("SELECT username, role FROM app_user_role WHERE username = ?"); } 设置为视图的ViewModel。您只需使用DataContext

绑定该属性即可

从评论中,如果你要绑定整个viewModel,因为转换器会做更多的东西,而不仅仅是转换类型,或者某些东西。看看这个:answer

相关问题