Bastien M.
Bastien M.

Reputation: 83

WPF DataGrid, How to bind property on custom DataGridColumn

I have a WPF DataGrid like this :

<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>

It's ItemSourceproperty is bound to a List of Agent in my DataContext, here is the code of the Agent class :

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;
    }
}

Each property of this class is bound to a column of my DataGrid. I'm experiencing trouble with the binding of WorkBalanceproperty which is bound to a custom column, here is my column template :

<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>

I can't figure out how to bind the Valueproperty of my Slider to the WorkBalanceproperty of my list. Any suggestions ?

Upvotes: 5

Views: 4876

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292425

The DataContext in the DataTemplate is the item, so you can just bind to WorkBalance directly:

Value="{Binding Path=WorkBalance}"

Upvotes: 3

Related Questions