开发者

WPF DataGrid conditional RowHeader problem

开发者 https://www.devze.com 2023-03-20 22:03 出处:网络
I want to conditionally show different RowHeader contents in the WPF datagrid. E.g. My Model has two properties, Name and IsSuperHero. If the row represents a super-hero I want to show textbox with \'

I want to conditionally show different RowHeader contents in the WPF datagrid. E.g. My Model has two properties, Name and IsSuperHero. If the row represents a super-hero I want to show textbox with 'SH' in the row-header.

I am trying to achieve this using datatriggers as below. The problem is, the text-box is shown only on one row (the last matching row). Below, I expect 'SH' to be shown against Superman and Batman b开发者_高级运维ut it shows up only against Batman. If I sort on Name column the records are sorted to 'Batman, John, Peter, Superman' and now the 'SH' header is shown against 'Superman' (that happens to be last matching record). Am I missing something here?

public class UserModel
{
    public String Name { get; set; }
    public Boolean IsSuperHero { get; set; }
    public UserModel (String name, Boolean issuperhero) { Name = name; IsSuperHero = issuperhero; }
}

public partial class MainWindow : Window
{

    private void Window_Loaded (object sender, RoutedEventArgs e){
    List<UserModel> list = new List<UserModel>();
    list.Add(new UserModel("Peter", false));
    list.Add(new UserModel("Superman", true));
    list.Add(new UserModel("John", false));
    list.Add(new UserModel("Batman", true));

    myDataGrid.ItemsSource = list;

    //Show Header 'SH' for Super Hero
    TextBox txtBox = new TextBox();
    txtBox.Text = "SH";

    Style rowStyle = new Style();
    DataTrigger dataTrigger = new DataTrigger();

    dataTrigger.Binding = new Binding("IsSuperHero");
    dataTrigger.Value = true;


    Setter setter = new Setter(DataGridRow.HeaderProperty, txtBox);

    dataTrigger.Setters.Add(setter);

    rowStyle.Triggers.Add(dataTrigger);
    myDataGrid.RowStyle = rowStyle;
}


The TextBox is only created once. You can add the TextBox as a resource in some dictionary and set x:IsShared to false, then reference it using the StaticResourceMarkupExtension, that way a new one will be created in every call.

(As x:Shared cannot be set in code this approach should be taken to XAML, i do not see any reason why one would want to do this in code in the first place)

0

精彩评论

暂无评论...
验证码 换一张
取 消