我的问题很容易重现。我使用视图模型从头开始创建了一个项目。正如您在"年龄"属性的setter中看到的那样,我有一个简单的逻辑。
public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int age;
public int Age
{
get
{
return age;
}
set
{
/*Age has to be over 18* - a simple condition in the setter*/
age = value;
if(age <= 18)
age = 18;
OnPropertyChanged("Age");
}
}
public MainViewModel(int age)
{
this.Age = age;
}
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
在主页.xaml
<Grid x:Name="LayoutRoot" Background="White">
<TextBox
Text="{Binding Path=Age, Mode=TwoWay}"
HorizontalAlignment="Left"
Width="100"
Height="25"/>
<TextBlock
Text="{Binding Path=Age, Mode=OneWay}"
HorizontalAlignment="Right"
Width="100"
Height="25"/>
</Grid>
和 MainPage.xaml.cs我只是实例化视图模型并将其设置为 DataContext。
public partial class MainPage : UserControl
{
private MainViewModel mvm;
public MainPage()
{
InitializeComponent();
mvm = new MainViewModel(20);
this.DataContext = mvm;
}
}
我希望如果文本框中输入的值低于 18,则此代码会将年龄设置为 18。方案:将值"5"插入文本框并按 Tab(要使绑定生效,文本框需要失去焦点)
案例 1:附加调试器 =>文本框值将为"5",文本块值将为"18"。-错
情况 2:调试器未附加 =>文本框值将为"18",文本块值将为"18" - 正确
似乎在附加调试器时,绑定在触发属性值更新的对象上无法按预期工作。仅当我们绑定到的属性在 setter 或 getter 中具有一些逻辑时,才会发生这种情况。
SL5 中是否发生了一些变化并且不再允许二传手中的逻辑?
配置:VisualStudio 2010 SP1SL 5 工具 5.1.30214.0SL5 SDK 5.0.61118.0IE 10
如果有人对答案感兴趣,请阅读这里:https://social.msdn.microsoft.com/Forums/en-US/f30a497c-d063-44b7-81ef-f979f186aee8/silverlight-5-binding-on-a-property-with-logic-in-its-setter-does-not-work-as-expected-when-debug-is?forum=silverlightgen