2011年11月10日

[WP7學習筆記] DataBinding (1)

假如我有一個資料結構是這樣    


public class TransactionRecord
{
public string CategoryID
{
get;set;
}
public string CategoryDesc
{
get;set;
}


public int Amount
{
get;set;
}
}

程式會透過資料存取取得所有的Category並顯示在ListBox中.


先定義主畫面


<phone:PhoneApplicationPage>
<!—省略—>


    <Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ScrollViewer>
<ItemsControl x:Name="_List">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border x:Name="_Border" x:FieldModifier="Private">
<!—省略—>
<Grid Tag="{Binding}" Height="120">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Foreground="Black" Grid.Column="0" Text="{Binding CategoryDesc}"/>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Foreground="Black" Text="{Binding CategoryID}"/>
<TextBlock Grid.Row="1" Foreground="Black" Text="{Binding Amount}"/>
</Grid>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</Grid>
</phone:PhoneApplicationPage>



其中的紅色粗體字型的地方即為我想要顯示的相對應的資料, 對應到資料結構的屬性. 然後在程式中指定



var records = Data.DAL.Instance.QueryRecords();
_List.ItemsSource = records;


結果


sp



如果我希望可以再畫面上修改金額, 並且直接把修改後的結果更心回資料集. 最簡單的做法是, 將顯示用的TextBlack改為TextBox, 並指定Binding Mode為Twoway如下



<TextBox Grid.Row="1" Height="84" Foreground="Black" InputScope="Number" Text="{Binding Amount, Mode=TwoWay}"/>


這時, 畫面上可以直接修改資料, 修改完後和下按鈕, 可以發現資料已經被修改了


private void button1_Click(object sender, RoutedEventArgs e)
{
var item = _List.Items[0] as Data.TransactionRecord;
MessageBox.Show(item.Amount.ToString());
}


sp2


這樣的方式, 資料是在離開TextBox時修改, 也就是Lost Focus時. 如果我希望的是在修改資料的當下就修改資料來源呢 ?


<TextBox Grid.Row="1" Height="84" Foreground="Black" InputScope="Number" Text="{Binding Amount, Mode=TwoWay,UpdateSourceTrigger=Explicit}" TextChanged="TextBox_TextChanged"/>



加入UpdateSourceTrigger=Explicit, 並指定TextChanged的Event Handler



        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
BindingExpression exp = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
exp.UpdateSource();
PageTitle.Text = "Amount=" + (_List.Items[0] as TransactionRecord).Amount.ToString();
}


修改的結果會立刻反應到資料來源

沒有留言:

Blog Archive

About Me