[英]How to update the value of a WPF binding from the C# code behind?
Used the following piece of code to bind a property on textbox.使用以下代码在文本框上绑定属性。 The property value is getting refreshed while text box value is modified is changed in UI.
在 UI 中更改文本框值时,属性值正在刷新。 But I assigned the value to textbox on code behind[txtNoOfSessions.Text = "1"] , but it is not reflecting the value in property.
但是我在后面的代码中将值分配给了文本框 [txtNoOfSessions.Text = "1"] ,但它没有反映属性中的值。
<TextBox x:Name="txtNoOfSessions"
Text="{Binding Path=NoOfSessions,Mode=TwoWay}"
Height="23" Width="120" />
Use INotifyPropertyChanged on the property.在属性上使用 INotifyPropertyChanged。 Otherwise, it will not update after the UI has loaded.
否则,它不会在 UI 加载后更新。
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
Example:例子:
public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}
set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
NotifyPropertyChanged("PhoneNumber");
}
}
}
这个答案需要更新或删除。
Usually I try not to update databound values from the code behind the UI, however if I have to I use the DataContext
of the UI object and update the bound property.通常我尽量不从 UI 后面的代码更新数据绑定值,但是如果我必须使用 UI 对象的
DataContext
并更新绑定属性。
In your example, it would look something like this:在您的示例中,它看起来像这样:
MyDataObject obj = txtNoOfSessions.DataContext as MyDataObject;
if (obj != null)
obj.NoOfSessions = "New Value";
Rachel is right, you cannot update bound values directly on the controls without overwriting the binding itself. Rachel 是对的,你不能在不覆盖绑定本身的情况下直接在控件上更新绑定值。
You can use the above or ((dynamic)this.DataContext).NoOfSession = "New Value";
您可以使用上面的或
((dynamic)this.DataContext).NoOfSession = "New Value";
is how I do it.我是怎么做的。
This way, the code will work without knowing the view model type.这样,代码将在不知道视图模型类型的情况下工作。 The view model could even be an
ExpandoObject
instead of a class and it will still work.视图模型甚至可以是一个
ExpandoObject
而不是一个类,它仍然可以工作。
Note that ExpandoObject
databinding is broken in Windows Store apps.请注意,
ExpandoObject
数据绑定在 Windows 应用商店应用中被破坏。
https://connect.microsoft.com/VisualStudio/feedback/details/836252/databinding-in-windows-store-apps-to-an-expandoobject-change-notification-not-working https://connect.microsoft.com/VisualStudio/feedback/details/836252/databinding-in-windows-store-apps-to-an-expandoobject-change-notification-not-working
txtNoOfSession.Text is bound. txtNoOfSession.Text 已绑定。 Set the value of the bound property.
设置绑定属性的值。 That is set NoOfSessions in your view model.
这在您的视图模型中设置了 NoOfSessions。
NoOfSessions = 1 NoOfSessions = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.