【发布时间】:2013-06-05 12:31:45
【问题描述】:
您好,我希望我能在这里找到一些帮助...
我正在使用 prism 和 MVVM 创建一个 WPF 应用程序。
我正在尝试创建一个我发现的附加属性here。
在我的 ViewModel 中,我通过
获得了焦点元素var control = Keyboard.FocusedElement;
那我做
string value = ExtraTextBehaviourObject.GetExtraText(control as UIElement);
但返回的值始终为空...谁能指出我正确的方向???
更新
public class ExtraTextBehaviourObject : DependencyObject
{
//Declare the dependency property
public static readonly DependencyProperty ExtraTextProperty;
static ExtraTextBehaviourObject()
{
//register it as attached property
ExtraTextProperty = DependencyProperty.RegisterAttached("ExtraText", typeof(string),
typeof(ExtraTextBehaviourObject));
}
//static function for setting the text
public static void SetExtraText(UIElement uiElement, string value)
{
if (uiElement != null)
{
uiElement.SetValue(ExtraTextProperty, value);
}
}
//static function for getting the text
public static string GetExtraText(UIElement uiElement)
{
if (uiElement != null)
{
return (string)uiElement.GetValue(ExtraTextProperty);
}
return "";
}
}
在 XAML 中设置代码
<dxe:TextEdit Text="{Binding Path=Customer.Comments, Mode=TwoWay}" AcceptsReturn="True" VerticalContentAlignment="Top"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Behaviors:ExtraTextBehaviourObject.ExtraText="HelloExtraText"
ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto"/>
【问题讨论】:
-
您或许还应该发布您的属性的实现。
-
感谢您的回复...我刚刚更新了“设置”代码
-
嗯,为什么你的课程来自
DependencyObject?由于您使用的是UIElement.GetValue()和UIElement.SetValue(...),因此不需要。 -
SetExtraText 永远不会被调用...这可能是问题...但是为什么呢?
-
在 XAML 中设置依赖属性时,WPF 不会调用 C# setter 方法。因此,未调用 SetExtraText 的事实并不意味着未设置属性值。无论如何,您确定
Keyboard.FocusedElement返回的元素是您所期望的吗?
标签: wpf mvvm attached-properties