wpf 中的绑定按钮内容值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24552183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding Button Content value in wpf
提问by JohnPaul
I am new to Wpf. Basically i achieve Button content Value change dynamically. here is my code.
我是 Wpf 的新手。基本上我实现了按钮内容值的动态变化。这是我的代码。
xaml:
xml:
<Button x:Name="btnTest" Content="NO" HorizontalAlignment="Left"VerticalAlignment="Top" Width="233" Height="40" Click="btnTest_Click" />
Cs file:
Cs文件:
private void btnTest_Click(object sender, RoutedEventArgs e)
{
if (btnTest.Content.ToString() == "NO")
{
btnTest.Content = "YES";
}
else if (btnTest.Content.ToString() == "YES")
{
btnTest.Content = "NO";
}
}
how can i achieve this same in "Binding" logic.
我怎样才能在“绑定”逻辑中实现同样的目标。
xaml:
xml:
<Button x:Name="btnTest" Content="{Binding ???}" HorizontalAlignment="Left"VerticalAlignment="Top" Width="233" Height="40" Click="btnTest_Click" />
could anyone please help?
有人可以帮忙吗?
回答by Orion
Just like this:
像这样:
Content="{Binding XXX, Mode=TwoWay, ValidatesOnDataErrors=True}"
This will get the value (for Contentin this case) from DataContext.
这Content将从DataContext.
EDIT:
编辑:
A)To create data context (code-behind version):
A)创建数据上下文(代码隐藏版本):
this.DataContext = new SomeViewModel();
You may put this for example in your constructor (in control/form/whatever)...
例如,您可以将其放在构造函数中(在控件/表单/任何形式中)...
B)And finally SomeViewModelis just a class:
B)最后SomeViewModel只是一个类:
public class SomeViewModel : IDataErrorInfo // sample interface
{
private string _xxx;
public string IP
{
get { return _xxx; }
set { _xxx = value; }
}
}
回答by grzkv
You can try this
你可以试试这个
Content= "{Binding RelativeSource={RelativeSource Self}, Path=YNText, Mode=OneWay}"
and add this to the code behind
并将其添加到后面的代码中
public string YNText {
get
{
_switch = !_switch;
return _switch ? "YES" : "NO";
}
}
private bool _switch;

