2011-08-03 9 views
4

私はWPFの相対初心者ですので、私に同行してください。私はfarenheitの値をcelciusに変換する単純なアプリケーションを持っています。これをMVVMにリファクタリングしてプレイすると思ったので、コードビハインドから別のクラスにすべてを移してから、プログラムでdataContextを設定しました。しかし、私は多くの.. 'コンテキストエラーに存在しません'。どこが間違っていますか?おかげWPF設定ウィンドウのデータコンテキスト

XAML

<Window x:Class="FarenheitCelciusConverter.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Temperature Converter" Height="500" Width="500" 
xmlns:local="clr-namespace:FarenheitCelciusConverter"> 
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Height="473" Width="488"> 

    <Label Height="28" HorizontalAlignment="Left" Margin="10,10,0,0" Name="lblF" VerticalAlignment="Top" Width="64" FontWeight="Bold">Farenheit</Label> 
    <Label Height="28" HorizontalAlignment="Left" Margin="10,42,0,0" Name="lblC" VerticalAlignment="Top" Width="64" FontWeight="Bold">Celcius</Label> 
    <TextBox Height="23" Margin="94,10,112,0" Name="tbFaren" VerticalAlignment="Top" Width="72" HorizontalAlignment="Left" /> 
    <TextBox Height="23" Margin="94,42,112,0" Name="tbCelcius" VerticalAlignment="Top" Width="72" HorizontalAlignment="Left" /> 
    <Button Margin="94,76,109,0" Name="btnConvert" Click="btnConvert_Click" Height="23" VerticalAlignment="Top" HorizontalContentAlignment="Center" Width="72" HorizontalAlignment="Left">Convert</Button> 
    <Image Name="image1" Stretch="Fill" Margin="94,112,240,228"> 
     <Image.Source> 
      <BitmapImage DecodePixelWidth="200" UriSource="C:\Users\Winston\Pictures\thermometer.jpg"/> 
     </Image.Source> 
    </Image> 
    <TextBlock FontWeight="Bold" Height="21" Margin="195,12,173,0" Name="tblCelci" VerticalAlignment="Top" /><TextBlock FontWeight="Bold" Height="21" Margin="195,44,0,0" Name="tblFarenh" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120" /><TextBlock FontWeight="Bold" Height="21" Margin="195,78,15,0" Name="tblCex" VerticalAlignment="Top" Foreground="Red" /> 
</Grid> 
</Window> 

コード

namespace FarenheitCelciusConverter 
{ 
/// <summary> 
/// Interaction logic for Window1.xaml 
/// </summary> 
public partial class Window1 : Window 
{ 
    public Window1() 
    { 
     InitializeComponent(); 
     DataContext = new ConverterViewModel(); 
    } 
} 

}

ビューモデル

背後

}

答えて

3

MVVMデータを使用してビュー(Window1の)とビューモデルからデータバインディングを介して前後に渡されます。だからあなたのテキストボックスのそれぞれは、あなたのViewModel内のパブリックプロパティにデータバインドする必要があります。

<TextBox Height="23" Margin="94,10,112,0" Name="tbFaren" VerticalAlignment="Top" Width="72" HorizontalAlignment="Left" Text="{Binding FahrenText}"/> 

そして、あなたのViewModelには、プロパティの値を取る彼らと何かをして、適切なテキストボックスにバインドされたプロパティを設定します。

このようにして、Viewmodelはロジックを実行しており、Viewは与えているルールに従って出力を解釈しています。後で、ViewModelを使用せずにViewのルールを変更することができますが、コードビヘイビアを使用すると、プログラムロジックとともにView設定を明示的に設定する必要があります。

また、ViewModelにiNotifyPropertyChangedを実装する必要があります。それ以外の場合は、データバインドされたプロパティ値が変更され、更新されないことをUIは認識しません。たとえば、this postをご覧ください。

Databinding in WPFのMSDN記事もここにあります。

関連する問題