在 wpf 中绑定单元格模板

binding celltemplate in wpf

我只是以编程方式从 devexpress 和所有单元格创建一个 GridControl 并以这种方式绑定它的 ItemsSource

var gridControlAzmayesh = new GridControl
            {
                View = tv,
                ItemsSource = new CollectionViewSource
                {
                    Source = list// include some column : id,name,last name 
                }.View
            };

现在我想在列中放置一个按钮并通过 id 绑定它,当单击按钮时打开一个用户控件和相应的行 id 但它不起作用 我的代码是:

var template = new DataTemplate();
        var buttonFactory = new FrameworkElementFactory(typeof(Button)) ;
        buttonFactory.SetValue(Button.ContentProperty,"....");
        buttonFactory.SetBinding(Button.TagProperty, //add id to tag
            new Binding()
            {
                XPath = "Id", // not binding work 
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
        buttonFactory.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler((sender, args) =>
        {
            var aa = ((Button)sender).Tag; // read tag
            var uc = new UcEditAzmayeshSabeghe((int) aa); //  initialize a user control to open whit row id 
            UcPopupSabeghe.Child = uc;
            UcPopupSabeghe.Placement = PlacementMode.Mouse;
            UcPopupSabeghe.StaysOpen = false;
            UcPopupSabeghe.AllowsTransparency = true;
            UcPopupSabeghe.IsOpen = true;
        }));
        template.VisualTree = buttonFactory;
        gridControlAzmayesh.Columns.Add(new GridColumn
        {
            FieldName = "Id",
            Header = "...",
            CellTemplate = template,
            Width = new GridColumnWidth(40, GridColumnUnitType.Pixel)
        });
        gridControlAzmayesh.View = new TableView() { UseLightweightTemplates = UseLightweightTemplates.Row };

我无法在 XAML 中创建我的 gridControl,因为我在许多不同的选项卡中创建了许多具有不同列的 gridControl:你为什么这么害怕 XAML 我知道,但是 XAML 不够灵活:太多了!

完全"id"没有绑定到按钮 我想获取每一行 ID 并将其绑定到按钮标签属性。

这是一个快速而简洁的示例,展示了如何创建带列的网格视图,其中一列承载 ToggleButton,单击后将打开 Popup

DataItem.cs

// The data model for the ListView
public class DataItem
{
  public DataItem(int id)
  {
    this.Id = id;
  }
  public int Id { get; set; }
}

ViewModel.cs

// The data source for the view
class ViewModel
{
  // Binding source for the ListView.ItemsSource
  public ObservableCollection<DataItem> DataItems { get; set; }
  
  public ViewModel()
  {
    this.DataItems = new ObservableCollection<DataItem>() 
    {
      new DataItem(111), 
      new DataItem(112)
    };
  }
}

UcEditAzmayeshSabeghe.xaml.cs

// Example UserControl which will display in the opened Popup
public partial class UcEditAzmayeshSabeghe : UserControl
{
  public static readonly DependencyProperty IdProperty = DependencyProperty.Register(
    "Id",
    typeof(int),
    typeof(UcEditAzmayeshSabeghe),
    new PropertyMetadata(default(int)));

  public int Id { get => (int) GetValue(UcEditAzmayeshSabeghe.IdProperty); set => SetValue(UcEditAzmayeshSabeghe.IdProperty, value); }

  public UcEditAzmayeshSabeghe()
  {
    InitializeComponent();
  }
}

UcEditAzmayeshSabeghe.xaml

<UserControl x:Class="UcEditAzmayeshSabeghe"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="450"
             d:DesignWidth="800">
  <TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UcEditAzmayeshSabeghe}, Path=Id}" />
</UserControl>

用法

MainWindow.xaml

<Window>
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>

  <ListView ItemsSource="{Binding DataItems}">
    <ListView.View>
      <GridView>
        <GridViewColumn Header="ID"
                        DisplayMemberBinding="{Binding Id}"
                        Width="40" />
        <GridViewColumn Header="Details">
          <GridViewColumn.CellTemplate>
            <DataTemplate DataType="{x:Type DataItem}">
              <Grid>
                <ToggleButton x:Name="OpenPopupButton" Content="Show Details" />
                <Popup Placement="Mouse"
                       IsOpen="{Binding ElementName=OpenPopupButton, Path=IsChecked}"
                       StaysOpen="False"
                       AllowsTransparency="True">
                  <UcEditAzmayeshSabeghe Id="{Binding Id}" />
                </Popup>
              </Grid>
            </DataTemplate>
          </GridViewColumn.CellTemplate>
        </GridViewColumn>
      </GridView>
    </ListView.View>
  </ListView>
</Window>

结果

这个解决方案很干净,看起来很愉快。 XAML 声明易于理解和维护。 UI 设计变得更加简单和冗长。