我有一個我定義的附加屬性。如何從Windows Store應用程序中的代碼綁定到c#中的自定義附加屬性?
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)」替換爲我的屬性,不會引發異常。
即使這個黑客不適合我。讓WMC9999擁有一個元素,其中包含一個自定義附加屬性。 –
看起來這裏有一個更確定的「不」: https://stackoverflow.com/questions/39550584/binding-from-code-to-a-custom-attached-property-in-winrt-uwp 但我沒有找到另一個臨時解決方法。 –