logo
down
shadow

Silverlight - Access the Layout Grid's DataContext in a DataGrid CellTemplate's DataTemplate?


Silverlight - Access the Layout Grid's DataContext in a DataGrid CellTemplate's DataTemplate?

By : user3854080
Date : October 28 2020, 08:00 PM
wish help you to fix your issue The problem seems to be that each row uses the datagrid source as its "new" datacontext kind of thing. So from each row you need to get out of the grid and point to someting higher in the hierarchy to get the parent datacontext. These solutions may help. Solution 2 worked for me when I encountered the same problem.
Solution 1 using the Locator
code :


Share : facebook icon twitter icon
Binding in behavior to datacontext of datatemplate in silverlight

Binding in behavior to datacontext of datatemplate in silverlight


By : applepain
Date : March 29 2020, 07:55 AM
I hope this helps you . From scratch - Silverlight 4 does not support bindings in Style Setters (this functionality is now available in SL5). For SL4 there is a workaround: SetterValueBindingHelper.
Not able to access Datagrid datacontext from datatemplate

Not able to access Datagrid datacontext from datatemplate


By : sanioky
Date : March 29 2020, 07:55 AM
I hope this helps you . , The problem is evident from your code...
code :
 <Control:SwapswireStatusImagePathConvertor.DealProp>
   <Control:DealObject 
         Deal="{Binding RelativeSource={RelativeSource FindAncestor, 
                        AncestorType={x:Type DataGrid}}, 
                        Path=Tag}"/>
 </Control:SwapswireStatusImagePathConvertor.DealProp>**
     <MultiBinding>
         <Binding Path="SwapswireBuyerStatusText"/>
         <Binding Path="SwapswireSellerStatusText"/>

         **<Binding RelativeSource="{RelativeSource FindAncestor, 
                  AncestorType={x:Type DataGrid}}"
                  Path="Tag"/>**

         <MultiBinding.Converter>
                <Control:SwapswireStatusImagePathConvertor 
                     AllGoodPath="/Resources/Done.png"
                     InProgressPath="/Resources/Go.png" 
                     WarningPath="/Resources/Warning.png" />
         </MultiBinding.Converter>
     </MultiBinding>
     String str1 = System.Convert.ToString(values[0]);
     String str2 = System.Convert.ToString(values[1]);
     ** this.DealProp = new DealObject();
     this.DealProp.Deal = values[2] as CMBSTrade; **

     if (DealProp.Deal.Swapswire) 
     {
           ....
     }
Accessing DataGrid from DataTemplate (silverlight)

Accessing DataGrid from DataTemplate (silverlight)


By : Ehima Prince
Date : March 29 2020, 07:55 AM
it fixes the issue After finding your DataTemplate you have to load whatever is inside it. For Example:
code :
var grid = dt.LoadContent() as DataGrid/StackPanel/AnyElement;
var item = grid.Children.First(c => c.Name == "element1");
WPF DataGrid - Databind to DataTable cell in CellTemplates DataTemplate

WPF DataGrid - Databind to DataTable cell in CellTemplates DataTemplate


By : James Ambler
Date : March 29 2020, 07:55 AM
I wish did fix the issue. The bindings in the template don't work because the DataContext is a DataRowView from the DataTable.
One solution is to change your template to set the DataContext to the object you want (of type A), then all your bindings would work (Name, GroupName, IsSelected). To do that, you will need to make a converter and have your template use it.
code :
<Window x:Class="WpfApplication17.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewModel="clr-namespace:WpfApplication17"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <viewModel:DataRowViewConverter x:Key="drvc" />
        <DataTemplate x:Key="ATemplate">
            <RadioButton DataContext="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell}, Converter={StaticResource drvc}}" Content="{Binding Path=Name}" GroupName="{Binding Path=GroupName}" IsChecked="{Binding Path=IsSelected}" />
        </DataTemplate>
        <DataTemplate x:Key="BTemplate">
            <CheckBox DataContext="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell}, Converter={StaticResource drvc}}" Content="{Binding Path=FullName}" IsChecked="{Binding Path=IsChecked}" />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Items}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" CanUserAddRows="False">
        </DataGrid>
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication17
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public System.Data.DataTable Items { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("StringColumn", typeof(string));
            dt.Columns.Add("IntColumn", typeof(int));
            dt.Columns.Add("AColumn1", typeof(A));
            dt.Columns.Add("AColumn2", typeof(A));
            dt.Columns.Add("BColumn1", typeof(B));
            dt.Columns.Add("BColumn2", typeof(B));

            dt.Rows.Add(
                "TestString",
                123,
                new A() { Name = "A1", GroupName = "GroupName", IsSelected = true },
                new A() { Name = "A2", GroupName = "GroupName", IsSelected = false },
                new B() { FullName = "B1", IsChecked=true },
                new B() { FullName = "B2", IsChecked=false }
            );

            Items = dt;
            this.DataContext = this;
        }

        private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            DataTemplate dt = null;
            if (e.PropertyType == typeof(A))
                dt = (DataTemplate)Resources["ATemplate"];
            else if (e.PropertyType == typeof(B))
                dt = (DataTemplate)Resources["BTemplate"];

            if (dt != null)
            {
                DataGridTemplateColumn c = new DataGridTemplateColumn()
                {
                    CellTemplate = dt,
                    Header = e.Column.Header,
                    HeaderTemplate = e.Column.HeaderTemplate,
                    HeaderStringFormat = e.Column.HeaderStringFormat,
                    SortMemberPath = e.PropertyName // this is used to index into the DataRowView so it MUST be the property's name (for this implementation anyways)
                };
                e.Column = c;
            }
        }
    }

    public class A
    {
        public string Name { get; set; }
        public string GroupName { get; set; }
        public bool IsSelected { get; set; }
    }

    public class B
    {
        public string FullName { get; set; }
        public bool IsChecked { get; set; }
    }

    public class DataRowViewConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DataGridCell cell = value as DataGridCell;
            if (cell == null)
                return null;

            System.Data.DataRowView drv = cell.DataContext as System.Data.DataRowView;
            if (drv == null)
                return null;

            return drv.Row[cell.Column.SortMemberPath];
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
Access the Window's DataContext from a DataTemplate in a DataGrid

Access the Window's DataContext from a DataTemplate in a DataGrid


By : Serenity
Date : March 29 2020, 07:55 AM
help you fix your problem Look at this usage of RelativeSource based binding, like {Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}. Here is example:
code :
    <DataGrid ItemsSource="{Binding Strings}" AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="String" Width="SizeToCells" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate DataType="{x:Type soDataGridHeplAttempt:ClicableItemsModel}">
                    <ListBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding ClickableItems}">
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal"></StackPanel>
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>
                        <ListBox.ItemContainerStyle>
                            <Style TargetType="ListBoxItem">
                                <Setter Property="ContentTemplate">
                                    <Setter.Value>
                                        <DataTemplate>
                                            <Button  Width="70" Content="{Binding }" Style="{StaticResource ButtonInCellStyle}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                                                     Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.Command}" 
                                                     CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}"/>
                                        </DataTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </ListBox.ItemContainerStyle>
                    </ListBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
private ICommand _command;
public ObservableCollection<ClicableItemsModel> Strings { get; set; }

public ICommand Command
{
    get { return _command ?? (_command = new RelayCommand<object>(MethodOnCommmand)); }
}

private void MethodOnCommmand(object obj)
{

}
   public ObservableCollection<String> ClickableItems { get; set; }
Related Posts Related Posts :
  • How to bring perforce client work space into sync with depot as of specific time of a specific date
  • How is a neural network called that is NOT convolutional
  • How to convert WSDL file to class file
  • iPhone Safari does not auto scale back down on portrait->landscape->portrait
  • how to build rabbitmq C client lib on windows
  • UITableView hide sectionindex but retain sections
  • Good .net4 profiler
  • UNIX Signal lost
  • How do I exclude the sources jar in mvn deploy?
  • RCP update site for multiple platforms
  • Setting checkstate on a ListWidgetItem
  • Learning programming language concepts
  • What is the command for Index optimization and update statistics for Oracle 10g and 11g?
  • Using Logger Filter with Not Equal condition Log4net
  • What is symbol table and how is it integrated into the executable?
  • 32-bit oracle 10g client to 64-bit oracle 10g server
  • Reducing memory usage by ISTIO side car
  • Azure Proxy Timing Out
  • Orders & Inventory DDD - Where should allocation/reservation be handled?
  • ngx bootstrap datepicker: how can i change weekdays?
  • Preserve whitespace and formatting for text returned from $.get jquery call
  • Web crawler update strategy
  • Looking for a fast hash-function
  • Unique ID for MS Word 2007 paragraph
  • What is the port for a hostname query?
  • GNUPLOT: 2d histogram from set of points
  • mac, netbeans 6.8, c++, sdl, opengl: compilation problems
  • Detect browser focus/out-of-focus via Google Chrome Extension
  • How to geocode a large number of addresses?
  • llvm-clang; function/variable names containing unicode charactrs
  • Gradle: Make a 3rd party jar available to local gradle repository
  • Real website/-application use cases where dependency injection was useful (excluding unit testing/mocks)?
  • Using XNamespace to create nicely formatted XML
  • How many elements can be held in a B-tree of order n?
  • What language should I learn to make 2D turn-based video games?
  • SQL Server CE - Internal error: Cannot open the shared memory region
  • djb2 Hash Function
  • Plone site files owner
  • What is CMS/Framework used in both of this website?
  • Keycloak authorization
  • How to Get ECI from ECGI
  • Access denied when starting SQL Server Express from command line
  • Is it possible for computers to tell time without a built in clock?
  • Are keys in B-tree nodes duplicated when the node is split?
  • How do chains work in Rainbow tables?
  • Pango-WARNING **: failed to choose a font, expect ugly output
  • Will a source-removal sort always return a maximal cycle?
  • Interesting metrics from JMX
  • Efficient way to ASCII encode UTF-8
  • Force IOException during file reading
  • problem with overriding autologin in spring security?
  • How to query the roster using JSJAC XMPP client
  • Checking if the application is running in NSIS before uninstalling
  • How does _mm_mwait work?
  • Best Practices for Managed SalesForce App Development?
  • Tiny C Compiler and Virus warnings
  • How do I programmatically add a widget to a container created from GtkBuilder?
  • limit concurrent user logins in Plone/Zope
  • Yii model tbl_* creates TblUserController and tblUser View
  • Eye-tracking for code editing
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk