簡體   English   中英

WPF中的綁定按鈕內容值

[英]Binding Button Content value in wpf

我是Wpf的新手。 基本上我可以實現Button內容的值動態變化。 這是我的代碼。

XAML:

<Button x:Name="btnTest"  Content="NO" HorizontalAlignment="Left"VerticalAlignment="Top" Width="233" Height="40" Click="btnTest_Click" />

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";
        }
    } 

我如何在“綁定”邏輯中實現相同的目的。

XAML:

  <Button x:Name="btnTest"  Content="{Binding ???}"   HorizontalAlignment="Left"VerticalAlignment="Top" Width="233" Height="40" Click="btnTest_Click" /> 

誰能幫忙嗎?

像這樣:

Content="{Binding XXX, Mode=TwoWay, ValidatesOnDataErrors=True}"

這將從DataContext獲得值(在這種情況下為Content )。

編輯:

A)創建數據上下文(代碼隱藏版本):

this.DataContext = new SomeViewModel();

您可以將其放在您的構造函數中(例如,在控件/窗體/任何地方)...

B)最后, SomeViewModel只是一個類:

public class SomeViewModel : IDataErrorInfo // sample interface
{
    private string _xxx;

    public string IP
    {
        get { return _xxx; }
        set { _xxx = value; }
    }
}

你可以試試這個

Content= "{Binding RelativeSource={RelativeSource Self}, Path=YNText, Mode=OneWay}"

並將其添加到后面的代碼中

public string YNText {
    get
    {
        _switch = !_switch;
        return _switch ? "YES" : "NO";
    }
}

private bool _switch;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM