我有一个带有两种方式绑定的 DataGrid,不知道为什么这不起作用,任何帮助将不胜感激。
我想使用双向绑定对象动态绑定到 DataGrid。
我使用了 XAML 中的列。如果我只是直接设置“ItemSource”属性 - 它可以工作,但是两个绑定不起作用 - 如果我在代码中更改我的源,则 Grid 不会反映该更改。
我创建了一个简单的示例来说明我的设置
这是 XAML
<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="356" d:DesignWidth="590" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid AutoGenerateColumns="False" Height="136" HorizontalAlignment="Left" Margin="71,116,0,0" Name="MyGrid" VerticalAlignment="Top" Width="453" >
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{Binding Path=Label, Mode=TwoWay}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" Header="Selected" />
<sdk:DataGridTextColumn Binding="{Binding Path=YValue, Mode=TwoWay}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Name" Width="*" />
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
</UserControl>
这是后面的代码
namespace SilverlightApplication1
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
ObservableCollection<Value> values = new ObservableCollection<Value>();
values.Add(new Value() { Label = "Sony", YValue = 50 });
values.Add(new Value() { Label = "Dell", YValue = 35 });
values.Add(new Value() { Label = "HP", YValue = 27 });
values.Add(new Value() { Label = "HCL", YValue = 17 });
values.Add(new Value() { Label = "Toshiba", YValue = 16 });
PagedCollectionView p = new PagedCollectionView(values);
Binding b = new Binding("ValuesBinding");
b.Mode = BindingMode.TwoWay;
b.Source = values;
MyGrid.SetBinding(DataGrid.ItemsSourceProperty, b);
}
}
public class Value : INotifyPropertyChanged
{
public String Label
{
get
{ return _label; }
set
{
_label = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Label"));
}
}
public Double YValue
{
get
{return _yValue;}
set
{
_yValue = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("YValue"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
Double _yValue;
String _label;
}
}