【发布时间】:2010-10-31 20:35:38
【问题描述】:
我有一个与this post 中描述的非常相似的问题。
我有一个 UserControl 来封装地址。这包含许多基本控件,主要是文本框。然后,我在每个属性的代码隐藏中都有支持依赖属性...
#region Line1
/// <summary>
/// Gets or sets the Line1.
/// </summary>
public string Line1
{
get
{
return (string)GetValue(Line1Property);
}
set
{
SetValue(Line1Property, value);
}
}
/// <summary>
/// The Line1 dependency property.
/// </summary>
public static readonly DependencyProperty Line1Property =
DependencyProperty.Register(
"Line1",
typeof(string),
typeof(AddressControl),
new PropertyMetadata(OnLine1PropertyChanged));
/// <summary>
/// Line1Property property changed handler.
/// </summary>
/// <param name="d">AddressControl that changed its Line1.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnLine1PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as AddressControl;
if (control != null)
{
control.OnLine1Changed((string)e.OldValue, (string)e.NewValue);
}
}
/// <summary>
/// Called when the Line1 changes.
/// </summary>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
private void OnLine1Changed(string oldValue, string newValue)
{
Line1TextBox.Text = newValue;
}
#endregion Line1
然后我在视图中使用这个控件...
<myControls:AddressControl Grid.Row="0" Grid.Column="3"
Line1="{Binding Path=Line1, Mode=TwoWay}"/>
这似乎在更新视图模型属性时设置了文本框值,正如您所期望的那样,但是我的问题是从用户控件获取更新回视图模型?
根据上面的链接,我应该检查控件上的 DataContext。 Surley的DataContext会和parent一样吗?
我希望这个问题的答案将适用于多个嵌套级别的控件,即。 Control1 用在 Control2 中,Control2 用在 Control3 中,重用的重点!
把我逼疯了,所以任何帮助真的很感激。
【问题讨论】:
标签: silverlight mvvm user-controls