WPF DataGrid,如何绑定自定义DataGridColumn上的属性

时间:2013-12-16 12:37:01

标签: c# wpf data-binding datagrid

我有一个像这样的WPF DataGrid:

<DataGrid x:Name="dtgAgent"
          ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window, AncestorLevel=1}, Path=DataContext.AgentList}"
                          AutoGenerateColumns="False">
          <DataGrid.Columns>
              <DataGridTextColumn Header="Agent Name" MaxWidth="140" MinWidth="80" SortDirection="Ascending" Width="100" CanUserReorder="False" IsReadOnly="True" Binding="{Binding Path=AgentName}"/>
              <DataGridTextColumn Header="Status"  Binding="{Binding Path=Status}" MinWidth="60"/>
              <DataGridCheckBoxColumn CanUserReorder="False" CanUserResize="False" CanUserSort="False" Header="Use" MaxWidth="40" MinWidth="40" Binding="{Binding Path=Used}" />
              <DataGridTemplateColumn CellTemplate="{StaticResource sliderTemplate}" CanUserReorder="False" CanUserResize="False" Width="140" Header="Work Balance (%)"/>
    </DataGrid.Columns>
</DataGrid>

ItemSource属性绑定到我的DataContext中的List代理,这是代理类的代码:

public class Agent
{
    public String AgentName { get;set; }
    public String Status { get; set; }
    public Boolean Used { get; set; }
    public Int16 WorkBalance { get; set; }

    public Agent(String AgentName)
    {
        this.AgentName = AgentName;
        Status = "Online";
        Used = true;
        WorkBalance = 50;
    }
}

此类的每个属性都绑定到我的DataGrid列。我遇到绑定到自定义列的WorkBalance属性的问题,这是我的列模板:

<DataTemplate x:Key="sliderTemplate">
    <Grid>
                <Slider HorizontalAlignment="Stretch" Minimum="0" Maximum="100" 
                        Value="{Binding Path=ItemSource.WorkBalance,RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/>
    </Grid>
</DataTemplate>

我无法弄清楚如何将Slider的Value属性绑定到列表的WorkBalance属性。有什么建议 ?

1 个答案:

答案 0 :(得分:2)

DataContext中的DataTemplate是项目,因此您只需绑定到WorkBalance directly

Value="{Binding Path=WorkBalance}"