我有一个已定义的附加属性。
namespace Controls
{
public class StateManager : DependencyObject
{
public static string GetVisualState(DependencyObject obj)
{
return (string)obj.GetValue(VisualStateProperty);
}
public static void SetVisualState(DependencyObject obj, string value)
{
obj.SetValue(VisualStateProperty, value);
}
// Using a DependencyProperty as the backing store for VisualStateProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty VisualStateProperty =
DependencyProperty.RegisterAttached("VisualState", typeof(string), typeof(StateManager),
new PropertyMetadata(null,
(s, e) => {
var stateName = (string)e.NewValue;
var ctrl = s as Control;
if (ctrl == null) throw new InvalidCastException("You can only attach VisualState properties to Controls");
if (!string.IsNullOrEmpty(stateName))
VisualStateManager.GoToState(ctrl, stateName, true);
}));
}
}
我可以在XAML中绑定到这个属性,像这样:
<controls:TitleStrip
controls:StateManager.VisualState=
"{Binding (controls:StateManager.VisualState), ElementName=pageRoot}"
Grid.Column="1"/>
现在,我需要在代码中动态创建与相同属性的绑定,所以我尝试了这样做:
var pp = new PropertyPath("(controls:StateManager.VisualState)");
var binding = new Binding() { Path= pp, Source=this };
BindingOperations.SetBinding(ct, StateManager.VisualStateProperty, binding);
很遗憾,设置绑定的Path属性会抛出一个ArgumentException异常,提示:"值不在预期范围内。"
如果我用"(Grid.Row)"替换我的属性,则不会抛出异常。