簡體   English   中英

C#WPF:View無法獲取屬性的更改

[英]C# WPF: View doesn't get the changes of property

我正在學習關於屬性綁定的wpf c#。 我創建了一個簡單的wpf應用程序。 我嘗試將矩形控件的寬度綁定到后面的代碼中的屬性“PageWidth”。 但不知何故它不起作用(視圖不會得到屬性的更改)。 我要實現的目標:-在代碼中將矩形的寬度初始化為100-如果單擊按鈕“ width ++”,則矩形的寬度將逐步增加10。我會在代碼中丟失某些內容嗎? 請提出建議,隨時修改我的代碼。 提前致謝。

XAML:

<Window x:Class="MyWpfApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Rectangle
        Fill="#FF6262BD"
        HorizontalAlignment="Left"
        Margin="23,24,0,0"
        Stroke="Black"
        VerticalAlignment="Top"
        Width="{Binding Path=PageWidth}"
        Height="100" />
    <Button
        Content="Width++"
        HorizontalAlignment="Left"
        Margin="35,129,0,0"
        VerticalAlignment="Top"
        Width="75"
        Click="Button_Click" />

</Grid>

xaml.cs:

using System;
using System.Windows;

namespace MyWpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            PageWidth = 100;
        }

        private Int32 _pageWidth;
        public Int32 PageWidth
        {
            get
            {
                return _pageWidth;
            }
            set
            { 
                if ( _pageWidth != value )
                {
                     _pageWidth = value;
                }
            }
         }

         private void Button_Click(object sender, RoutedEventArgs e)
         {
             if ( PageWidth <= 200 )
             {
                  PageWidth += 10;
             }
         }
     }
 }

您的代碼中存在兩個問題:

  • 您沒有設置DataContext ,因此綁定沒有引用(它不知道應該從哪個對象獲取PageWidth屬性)
  • PageWidth不是依賴項屬性,不會引發PropertyChanged事件,因此,當值更改時,無法通知綁定系統。

要解決這些問題,您應該:

  • 將DataContext設置為窗口本身:

     // in the constructor DataContext = this; 
  • 使MainWindow類實現INotifyPropertyChanged接口,並更改PageWidth屬性,以使其引發PropertyChanged事件:

     public partial class MainWindow : Window, INotifyPropertyChanged { ... public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } private Int32 _pageWidth; public Int32 PageWidth { get { return _pageWidth; } set { if ( _pageWidth != value ) { _pageWidth = value; OnPropertyChanged("PageWidth"); } } } ... 

暫無
暫無

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

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