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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:04:31  来源:igfitidea点击:

Binding Button Content value in wpf

c#wpfxaml

提问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;