开发者

Trouble sending an event to another class in C#/WPF

I'm relatively new to OOD, C#, WPF, but trying to learn. So I have a main XAML that has a few controls in it. One control is a Dat开发者_开发知识库aGrid (dtGrid). The DataGrid has its own code behind and has some methods for its class. I am trying to create an event for when the scroll is done horizontally. I have this:

 private void dtGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        if (e.HorizontalChange != 0)
        {
            // update some stuff to main XAML
        }
    }

I don't see how the dtGrid has any visibility of the main XAML. Since the dtGrid (DataGrid control) has its own code behind it where I put this method, I have no reference to the other controls that are in the main XAML by their Name. Is there a way to get around this? Thanks.

Edit: Additional Code and some psuedo code for brevity So my main class that has the main XAML:

<UserControl>
<GroupBox Header="Sample" Grid.Row="2" Margin="5, 0, 5, 0" FontSize="12" FontFamily="Arial" FontWeight="Bold">
            <View:SampleControl x:Name="SampleControl" Background="Transparent" />
        </GroupBox>
</UserControl>

I have code behind this XAML where I need to make the update to the other object when the scroll is changed. However, the problem I have is I have another XAML for the SampleControl which is:

<some UserControl and the namespaces>
<DataGrid x:Name="dtGridReads"  AutoGenerateColumns="False" 
            VirtualizingStackPanel.IsVirtualizing="True"                                       
            VirtualizingStackPanel.VirtualizationMode ="Standard" 
              EnableColumnVirtualization="False"
              EnableRowVirtualization="False"
            ScrollViewer.IsDeferredScrollingEnabled="True"
            CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserSortColumns="True"
             ItemsSource ="{Binding}" Block.TextAlignment="Center"
             CanUserAddRows="False" CanUserDeleteRows="False" FrozenColumnCount="1"
               GridLinesVisibility="None" FontFamily="Arial" FontSize="10" Background="White"
              ScrollViewer.ScrollChanged="dtGridReads_ScrollChanged" >

and then I have code-behind behind this XAML as well. So I'm not sure where everything goes and who can communicate to who.


The event of the datagrid is public and should be used outside the datagrid, most likely in the Window or UserControl that's hosting it:

In window (or any class other than the DataGrid class)

DataGrid dg = new DataGrid();
dg.ScrollChanged += DoSomething;


private void DoSomething(object sender, ScrollChangedEventArgs e)
{
    if (e.HorizontalChange != 0)
    {
        // update some stuff to main XAML which should now be available
    }
}

Update

If you want to see how to subscribe to the event from XAML you can use:

<DataGrid ScrollChanged="DoSomething" />
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜