我在代码中有一个对象:
public class UserLogin
{
bool _IsUserLogin = false;
public bool IsUserLogin
{
get { return _IsUserLogin; }
set { _IsUserLogin = value; }
}
public UserLogin()
{
_IsUserLogin = false;
}
}
....
public static UserLogin LoginState;
.....
LoginState = new UserLogin();
我需要将绑定(bind)设置为 Button.IsEnabled 属性。 IE。当用户尚未登录时 - 某些按钮被禁用。这是怎么做到的?我在 xaml 中尝试过:
<Button DataContext="LoginState" IsEnabled="{Binding Path=IsUserLogin}">
但是,这不起作用,OutputWindow 说:System.Windows.Data 错误:39:BindingExpression 路径错误:在“对象”上找不到“IsUserLogin”属性。
我也尝试在代码中将 Button.DataContext 属性设置为 LoginState,但有 XamlParseException。我也读过这个 [ WPF - Binding in XAML to an object created in the code behind但仍然无法设置绑定(bind)。
[1]:WPF - Binding in XAML to an object created in the code behind .请帮忙!
最佳答案
您会收到 XamlException,因为编译器找不到名为“LoginState”的 (XAML)-Element。
在程序代码中设置按钮的 DataContext。然后它应该工作。
public void SetDataContextOfButton() {
UserLogin login = new UserLogin();
button.DataContext = login; //Assumes that you name your Button in XAML with x:Name="button"
}
关于wpf - 如何将 xaml 中的绑定(bind)设置为我自己的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2480013/