【发布时间】:2016-12-21 04:17:43
【问题描述】:
为了简化我的问题,在我的应用程序中,我想将用户的输入全部更改为大写。所以当TextBox失去焦点时,“foo”应该显示为“FOO”。
我的 Xaml:
<Page x:Class="App12.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:App12"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.DataContext>
<local:MainViewModel />
</Page.DataContext>
<StackPanel Margin="10,50,10,10" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBox Text="{Binding Name1, Mode=TwoWay}" />
<TextBox Text="{x:Bind Path=vm.Name2, Mode=TwoWay}" />
<Button HorizontalAlignment="Center">Just a control for the TextBox to lose focus</Button>
</StackPanel>
</Page>
我的视图模型
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace App12
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
}
private string _name1 = "something";
public string Name1
{
get
{
return _name1;
}
set
{
_name1 = (string)value.ToUpper();
OnPropertyChanged();
}
}
private string _name2 = "something";
public string Name2
{
get
{
return _name2;
}
set
{
_name2 = (string)value.ToUpper();
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged( [CallerMemberName] string propertyName = null )
{
var handler = PropertyChanged;
handler?.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
}
}
}
还有我的代码隐藏
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App12
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
MainViewModel vm;
public MainPage()
{
this.InitializeComponent();
DataContextChanged += MainPage_DataContextChanged;
}
private void MainPage_DataContextChanged( FrameworkElement sender, DataContextChangedEventArgs args )
{
vm = (MainViewModel)DataContext;
}
}
}
当我在 UWP 应用(第一个文本框)中使用经典绑定时,此代码不起作用
我看到 setter 被调用, OnNotifyPropertyChanged 也被调用,并且处理程序不为空。变量 _text 被分配了它的新值就好了(全部大写),但是我从来没有看到公共变量 Text 的 getter 被调用。 我还尝试了一个转换器(实现了 ConvertBack),结果相同。 但是,使用 x:Bind(第二个文本框),它确实有效。
在 WPF 中,这也可以按预期工作。 我错过了什么还是绑定改变了?根据 Microsoft 告诉我们的内容以及我所看到的内容,它不应该有。
【问题讨论】:
标签: c# xaml data-binding visual-studio-2015 uwp-xaml