2012-10-11 34 views
2

的成員,我必須在應用程序主窗口類的私人領域如何WPF文本框綁定到propperty是應用程序的主窗口

private static Double myValue; 

。還有(在主窗口類)我定義的屬性

public static Double MytValue 
{ 
    get { return myValue; } 
} 

在主窗口類的結構我有一個文本框。我需要將它綁定到MytValue屬性。在XAML中我寫道:

<TextBox Name="tbxMyValue" Grid.Row="1" Grid.Column="2" TextAlignment="Center" 
     Text="{Binding Path=MyValue}" Width="Auto" Margin="10,0,10,15" IsEnabled="True" /> 

但它沒有效果。我在TextBox中看不到任何東西,而myValue變量有一個值。爲什麼?請幫幫我。

+0

它是 「myvalue的」 或 「MytValue」? – rossisdead

+1

我收到你的赦免 - 這是我的課程價值。 – user1688773

回答

0

這不是它的工作原理。綁定到靜態屬性; {Binding Source = {x:Static local:Application.MyValue}}

請注意,您的字段需要屬性& public。如果你想使用你的解決方案,你需要將DataContext設置爲{RelativeSource Self}。

0

在文件MainWindow.xaml.cs在構造函數中添加此行:

DataContext = this; 

InitializeComponent();

+0

所以如果myvalue的以編程方式動態更改文本框中的值將每次作相應改變? – user1688773

4

您需要設置窗口後面的DataContext進行裝訂工作

有兩層到WPF的應用程序:UI層和數據層。

應用程序的數據層開始爲null,您可以使用DataContext屬性對其進行設置。

每當你在WPF做一個基本的約束力,你要綁定到DataContext。所以Text="{Binding Path=MyValue}"實際上是說「從當前DataContext獲得MyValue財產」。

你可以簡單地設置DataContext在後面的代碼:

MyWindow.DataContext = this; 

或者你可以使用一個RelativeSource結合來告訴WPF從別的地方得到MyValue屬性,比如告訴它從一開始就

Text="{Binding Path=MyValue, RelativeSource={ 
    RelativeSource AncestorType={x:Type Window}}}" 

其實我有一篇關於我對DataContext,我建議你閱讀博客,如果你是新來女:最近的窗口它向上導航時VisualTree發現PF和DataContextWhat is this "DataContext" you speak of?

+0

謝謝你的幫助。 – user1688773

+0

恭喜,不錯的答案! – Ewerton

5

我喜歡設置的DataContext在窗部件

<Window x:Class="Gabe3a.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:Gabe3a" 
     xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" 
     xmlns:System="clr-namespace:System;assembly=mscorlib" 
     DataContext="{Binding RelativeSource={RelativeSource self}}" 
     Title="Gabriel Main Ver 3a01" Icon="faviconw.ico" Height="600" Width="800"> 
+0

不錯,我從來沒有見過這個。 – Ewerton

+1

@Ewerton,但不夠好的+1? – Paparazzi

+0

+ 1ned :) @Blam。 – Ewerton