2012-02-08 113 views
0

如何根据复选框选择更改WPF中的网格视图内的文本块的值。在WPF中的网格视图是从一个SQL表中填充的,这个表的ID和值为columns.Value这里是YES或NO.I正在使用LINQ to sql。 我有一个复选框与网格视图中的每个ID关联。当用户选择一些行时,我必须将更改保存回数据库。GridView CheckBox绑定

因此,根据该选择我必须要改变的值字段行中以这种方式:

如果在网格视图的“值”字段中的文本是“YES”,那么我必须改变它为“否” 如果网格视图的“值”字段中的文本是“否”,那么我必须将其更改为“是”

我能够将数据填充到gridview,但我我不确定我的问题在上述情况下是否适合WPF和c#,需要一些指导。

回答

0

做到这一点,最好的方法是既文本块和在数据模型中的复选框,以相同的后端域,然后结合使用代码转换器。

这是一个简单的例子。

假设你有一个布尔属性下面这个简单的视图模型:

class SimpleViewModel: INotifyPropertyChanged 
{ 
    private bool _checked; 
    // The property to bind to 
    public bool Checked 
    { 
     get { return _checked; } 
     set { _checked = value; OnPropertyChanged("Checked"); } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    public void OnPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

这里也是一个文本块一个简单的页面和文本字段都绑定到相同的后端领域。

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:WpfApplication1" 
    Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <local:SimpleViewModel x:Key="simpleViewModel" /> 
     <local:BoolToStringConverter x:Key="boolToStringConverter" /> 
    </Window.Resources> 
    <Grid DataContext="{StaticResource simpleViewModel}"> 
     <StackPanel> 
      <TextBlock Text="{Binding Checked, Converter={StaticResource boolToStringConverter}}" /> 
      <CheckBox Content="something" IsChecked="{Binding Checked}" /> 
     </StackPanel> 
    </Grid> 
</Window> 

现在注意到文本块绑定语句包含一个转换器语句。 Text="{Binding Checked, Converter={StaticResource boolToStringConverter}}"

这里的转换器非常简单。它检查值是否为真,并返回是,否则返回NO。

public class BoolToStringConverter:IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (value == null) return null; 

     if ((bool)value == true) 
      return "YES"; 
     else 
      return "NO"; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     // this scenario is not needed since the text block is read only 
     throw new NotImplementedException(); 
    } 
} 
0

您需要处理事件。点击控件并点击闪电大胆,并在c#后面的代码中执行它。关键字是事件。 OnChanged,Onclicked,onrowchange等位于该控件的属性框中,并更改代码中的值。