簡體   English   中英

WPF中的雙向綁定

[英]Two Way Binding in WPF

我是WPF的新手,對此我有一個疑問。 這可能是非常愚蠢的,所以請原諒。

我正在做一個項目,將文本框等綁定到單例類中的靜態屬性。 我的問題是,雙向綁定無法正常工作。 當文本框更改時,我可以看到屬性的值更改了,但是當屬性更改時,我看不到文本框的文本也更改了。

為了了解發生了什么,我編寫了一個帶有相關代碼的小應用程序。 請在下面找到代碼。

在下面的代碼中,我將在不同位置更改文本框和source屬性中的文本,並注意我的觀察。 如果有人可以告訴我我做錯了什么,並指出正確的方向,我將不勝感激。

我也嘗試過INotifyPropertyChanged,但是由於靜態屬性,它帶來了問題。 為靜態屬性實現INotifyPropertyChanged時,是否有其他方法。

在此先感謝阿比。

XAML:

<Page x:Class="TestBindingApp.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Prefs="clr-namespace:TestBindingApp"
  xmlns:cm="clr-namespace:System.ComponentModel;assembly=System"
  xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
  xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
Title="Page1" Loaded="Page_Loaded">
<Page.Resources>
    <Prefs:Class1 x:Key="TClass"></Prefs:Class1>
</Page.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal" Margin="15 5 5 0" Height="20">
        <TextBlock Name="txbBankNumber" Margin="50 0 0 0" Padding="2">Bank Account Number :</TextBlock>
        <TextBox Name="txtBankNumber" Margin="10 0 0 0" Width="100" MaxLength="8" HorizontalAlignment="Left">
            <TextBox.Text>
                <Binding Source="{StaticResource TClass}" Path="AccountNumber" Mode="TwoWay" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged">
                </Binding>
            </TextBox.Text>
        </TextBox>
    </StackPanel>

</Grid>

XAML.CS:

namespace TestBindingApp
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
    public Page1()
    {

        InitializeComponent();

        txtBankNumber.Text = "ABC";
 // I can see the property AccountNumber changing here
        Class1.AccountNumber = "123456";
 // Value in txtBankNumber doesn't change here
    }

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        txtBankNumber.Text = "ABCDE";
 // I can see the property AccountNumber changing here

        Class1.AccountNumber = "12345678";
 // Value in txtBankNumber doesn't change here

    }
}

}

班級Class1:

using System.ComponentModel;

namespace TestBindingApp
{
public class Class1
{
    // Singleton instance
    private static Class1 instance;
    private static string _accountNumber;
    public Class1()
    {

    }

    // Singleton instance read-only property
    public static Class1 Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Class1();
            }
            return instance;
        }
    }

    public static string AccountNumber
    {
        get
        {
            return _accountNumber;
        }
        set
        {
            if (value != _accountNumber)
            {
                _accountNumber = value;
            }
        }
    }
}

}

=====================

無法在評論中發布我更新的代碼,因此更新了我的原始帖子。

下面是我的更新代碼,其中包含“ if(PropertyChanged!= null)”,但它給了我一個錯誤-“非靜態字段,方法或屬性'TestBindingApp.Class1.NotifyPropertyChanged(串)'”。

我剛剛開始學習WPF,因此,如果您可以詳細解釋,那將非常有幫助。 謝謝你的耐心。

using System.ComponentModel;

namespace TestBindingApp
{
public class Class1: INotifyPropertyChanged
{
    // Singleton instance
    private static Class1 instance;
    private static string _accountNumber;
    public event PropertyChangedEventHandler PropertyChanged;

    public Class1()
    {

    }

    // Singleton instance read-only property
    public static Class1 Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Class1();
            }
            return instance;
        }
    }

    public static string AccountNumber
    {
        get
        {
            return _accountNumber;
        }
        set
        {
            if (value != _accountNumber)
            {
                _accountNumber = value;
                NotifyPropertyChanged("AccountNumber");
            }
        }
    }

    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    } 

}

}

==============

6月23日,英國時間上午9:53更新

嗨,Arcturus,我已經將屬性更改為非靜態的,但是它仍然沒有像我期望的那樣運行。 我是否期望它執行原本不打算做的事情,還是我做錯了什么。 在下面的代碼中,我希望文本框將帳號顯示為12345678(或123456),但仍顯示為123。在調試模式下,我可以看到PropertyChanged事件在每個屬性更改語句之后都能正確執行,但是文本框不變。 綁定僅在初始化(InitializeComponent())時才會生效,還是我在這里丟失了一些東西?

頁面代碼隱藏

namespace TestBindingApp
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
    public Page1()
    {
        Class1.Instance.AccountNumber = "123";
        InitializeComponent();
        Class1.Instance.AccountNumber = "123456";
    }

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        Class1.Instance.AccountNumber = "12345678";
    }
}
}

Class1.cs

namespace TestBindingApp
{
public class Class1: INotifyPropertyChanged
{
    // Singleton instance
    private static Class1 instance;
    private static string _accountNumber;
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public Class1()
    {

    }

    // Singleton instance read-only property
    public static Class1 Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Class1();
            }
            return instance;
        }
    }

    public string AccountNumber
    {
        get
        {
            return _accountNumber;
        }
        set
        {
            if (value != _accountNumber)
            {
                _accountNumber = value;
                OnPropertyChanged("AccountNumber");
            }
        }
    }

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    } 

}
}

您確實需要INotifyPropertyChanged接口:

using System.ComponentModel;

namespace TestBindingApp
{
public class Class1
{
    // Singleton instance
    private static Class1 instance;
    private string _accountNumber;
    public Class1()
    {

    }

    // Singleton instance read-only property
    public static Class1 Instance
    {
    get
    {
        if (instance == null)
        {
        instance = new Class1();
        }
        return instance;
    }
    }

    public string AccountNumber
    {
    get
    {
        return _accountNumber;
    }
    set
    {
        if (value != _accountNumber)
        {
        _accountNumber = value;
            NotifyPropertyChanged("AccountNumber");
        }
    }
    }

        public event PropertyChangedEventHandler PropertyChanged;


    private void NotifyPropertyChanged(string property)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
}

您從靜態成員調用NotifyPropertyChanged,但NotifyPropertyChanged本身不是靜態的。

有兩種解決方法:使AccountNumber不是靜態的或為您對NotifyPropertyChanged的調用提供實例(例如“ Instance.NotifyPropertyChanged(...)”)

暫無
暫無

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

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