如前所述,這裏的問題是DataGridTextColumn不在邏輯或可視化樹中。 另一種解決方案是基於提供綁定的綁定代理的此方法。 https://stackoverflow.com/a/46787502/5381620
源碼
<DataGrid ItemsSource="{Binding Lines}" AutoGenerateColumns="False" >
<DataGrid.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}"/>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="ProductId1" Binding="{Binding Path=Result[0]}" Width="{Binding Data.Columns[0].Width, Source={StaticResource proxy}, Mode=TwoWay}" />
<DataGridTextColumn Header="ProductId2" Binding="{Binding Path=Result[1]}" Width="{Binding Data.Columns[1].Width, Source={StaticResource proxy}, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
class BindingProxy : Freezable
{
//Override of Freezable
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}
public class Column : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected internal void OnPropertyChanged(string propertyname)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
public DataGridLength Width
{
get { return m_width; }
set { m_width = value; OnPropertyChanged("Width"); }
}
DataGridLength m_width;
}
對於此實現直接使用List<Column>
或在的ObservableCollection其他的DataContext調整結合。
你的數據結構是什麼樣的?包含'Name'屬性的相同對象是否也包含您的'GridNameWidth'屬性? – Rachel
正確,同一個對象包含我的Name對象。 – Luke101
通過模型屬性設置視覺效果的寬度不是mvvm。 – Will