简体   繁体   English

如何从 WPF 后面的代码访问 XAML 按钮

[英]How to access XAML button from code behind WPF

My code:我的代码:

<DataGrid  HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden"  BorderBrush="#83D744" IsSynchronizedWithCurrentItem="False" VerticalGridLinesBrush="Transparent" Grid.Column="0"   RowHeaderWidth="0" CanUserAddRows="False" AutoGenerateColumns="False"  x:Name="datagrid1" Margin="10,150,8,50" Background="Transparent" RowBackground="#FF494949"  VerticalContentAlignment="Center" HorizontalContentAlignment="Center" ItemsSource="{Binding}">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="Background" Value="#83D744"/>
            <Setter Property="Opacity" Value="1"/>
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="FontSize" Value="18"/>
            <Setter Property="FontFamily" Value="Arial"/>
            <Setter Property="Height" Value="50"/>
        </Style>


<Style x:Key="TextInCellCenter" TargetType="{x:Type TextBlock}" >
    <Setter Property="TextAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type TextBlock}" x:Key="RightAligElementStyle">
    <Setter Property="TextAlignment" Value="Right"/>
</Style>
<Style TargetType="{x:Type TextBlock}" x:Key="LeftAligElementStyle">
    <Setter Property="TextAlignment" Value="Left"/>
</Style>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
           Color="Transparent"/>
</DataGrid.Resources>


<DataGrid.Columns >
    <DataGridTextColumn Binding="{Binding ProductName}"     ElementStyle="{StaticResource LeftAligElementStyle}"     Header="NAZIV ARTIKLA" MinWidth="350"    Foreground="White" FontSize="20" FontFamily="Verdana" />
    <DataGridTextColumn Binding="{Binding Quantity}"        ElementStyle="{StaticResource TextInCellCenter}"         Header="KOLIČINA"   MinWidth="200" Foreground="White"      FontSize="20" FontFamily="Verdana" />
</DataGrid.Columns>

<DataGrid.GroupStyle>
    <!-- Style for groups at top level. -->
    <GroupStyle>
        <GroupStyle.ContainerStyle>
            <Style TargetType="{x:Type GroupItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type GroupItem}">
                            <Expander IsExpanded="True"  Background="Black" Opacity="0.7">
                                <Expander.Header >
                                    <DockPanel Height="50" Margin="0,0,0,0"  Name="dockPanel" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=ActualWidth}">

                                        <Button Name="btnFinishOrder" Content="Finish Order" Margin="0,0,55,5" DockPanel.Dock="Right" Click="btnFinishOrder_Click" FontSize="12" BorderThickness="1.5" HorizontalAlignment="Left"  VerticalAlignment="Bottom"  HorizontalContentAlignment="Center" VerticalContentAlignment="Center"  Foreground="#83D744"  Background="Transparent"  BorderBrush="#83D744" Width="130"   Height="40">
                                             <Button.Template>
                                                <ControlTemplate TargetType="Button">
                                                <Border BorderThickness="{TemplateBinding BorderThickness}"
                                                        BorderBrush=    "{TemplateBinding BorderBrush}"
                                                        Background=     "{TemplateBinding Background}">
                                                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                                                </Border>
                                                </ControlTemplate>
                                             </Button.Template>
                                         </Button>

                                         <Button Name="btnTakeIt" Click="btnTakeIt_Click"  Content="Take it" Margin="0,0,20,5" DockPanel.Dock="Right" FontSize="12" BorderThickness="1.5" HorizontalAlignment="Left"  VerticalAlignment="Bottom"  HorizontalContentAlignment="Center" VerticalContentAlignment="Center"  Foreground="#83D744"  Background="Transparent"  BorderBrush="#83D744" Width="130"   Height="40">
                                             <Button.Template>
                                                <ControlTemplate TargetType="Button">
                                                <Border BorderThickness="{TemplateBinding BorderThickness}"
                                                        BorderBrush="{TemplateBinding BorderBrush}"
                                                        Background="{TemplateBinding Background}">
                                                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                                                </Border>
                                                </ControlTemplate>
                                             </Button.Template>
                                        </Button>
                                        <TextBlock FontWeight="Normal" FontFamily="Verdana" FontSize="20" Height="25" Foreground="#83D744" Text="{Binding Path=Name,StringFormat= Number of Order:# {0}}" />

                                    </DockPanel>
                                </Expander.Header>
                                <Expander.Content>
                                    <ItemsPresenter />
                                </Expander.Content>
                            </Expander>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </GroupStyle.ContainerStyle>
    </GroupStyle>
</DataGrid.GroupStyle>

在此处输入图片说明

There you can see guys, when I click on button Click="btnTakeIt_Click" I programaticaly change buttons text to "Order in progress."在那里你可以看到伙计们,当我点击按钮Click="btnTakeIt_Click"我以编程方式将按钮文本更改为“正在订购”。 and I update field in my database IsInProgres to 1 - true, code is here:我将数据库IsInProgres字段更新为 1 - true,代码在这里:

 private void btnTakeIt_Click(object sender, RoutedEventArgs e)
    {
        Button b = sender as Button;

        CollectionViewGroup group = b.DataContext as CollectionViewGroup;
        var x = group.Name;
        int orderNumber = Convert.ToInt32(x);

        b.BorderBrush = null;
        b.Content = "Order is in progress";
        b.FontSize = 12;

        OrdersController.SetOrderInProgressByID(orderNumber);

    }

But what is happening, because I'm refreshing my grid every 20 seconds my button content is becoming again like it's on default "Take it!"但是发生了什么,因为我每 20 秒刷新一次我的网格,我的按钮内容又变得像默认的“接受它!” because that's whats written in XAML.因为那是用 XAML 编写的。

Like this:像这样: 在此处输入图片说明

This is my code behind (refresh every few seconds):这是我背后的代码(每隔几秒刷新一次):

 public MainWindow()
{
    try
    {


        InitializeComponent();


        this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
        this.WindowState = WindowState.Maximized;

        var ordersList = OrdersController.localOrders();


        collectionViewSource.Source = ordersList;
        collectionViewSource.GroupDescriptions.Add(new PropertyGroupDescription("NumberOfOrder"));
        DataContext = collectionViewSource;

        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(20);
        timer.Tick += timer_Tick;
        timer.Start();

    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

void timer_Tick(object sender, EventArgs e)
{

    var ordersList = OrdersController.localOrders();
    collectionViewSource.Source = null;
    collectionViewSource.Source = ordersList;

    DataContext = collectionViewSource;

    datagrid1.ScrollIntoView(datagrid1.Items[datagrid1.Items.Count - 1]);
}

} }

So my question is could I somehow loop my localOrders and check if NumberOfOrder has IsInProgress = 1 and simply set this:所以我的问题是我能否以某种方式循环我的 localOrders 并检查NumberOfOrder是否具有IsInProgress = 1并简单地设置:

btnTakeIt.Content="Order in progress.." 

So everytime my grid refresh I can loop my orders, and check is order InProgress and after that I can set button btnTakeIt content to "Order in progress.."所以每次我的网格刷新我可以循环我的命令,并检查是为了InProgress之后,我可以设置按钮btnTakeIt内容为“在建订单。”

Or if there is any other way, I am opened to try it!或者如果有其他方法,我愿意尝试!

PS I tried allready but my btnTakeIt is not accessible in code behind :( PS 我已经试过了,但我的 btnTakeIt 在后面的代码中无法访问:(

EDIT:编辑:

 void timer_Tick(object sender, EventArgs e)
    {
        Button MyButton = FindChild<Button>(datagrid1, "btnTakeIt");

        var ordersList = OrdersController.localOrders();
        collectionViewSource.Source = null;
        collectionViewSource.Source = ordersList;
        foreach (var item in ordersList)
        {
            if (item.IsInProgress== true)
            {
                MyButton.Content = "Order is in progress";
            }
        }

        DataContext = collectionViewSource;


    }

Can I do it like this?我可以这样做吗? I checked debuger and it is entering inside of if statement and when I look at breakpoint it acctualy changes content but on grid I can not see anything changed :(我检查了调试器,它正在进入 if 语句,当我查看断点时,它确实更改了内容,但在网格上我看不到任何更改:(

EDIT:编辑:

在此处输入图片说明

I have to mention that my class Product is contained in my OrdersController :)我不得不提到我的产品类包含在我的 OrdersController 中:)

@Ayuman what do you think about this: @Ayuman 您对此有何看法:

<Button Name="btnTakeIt"   DataContext="{Binding Items[0]}" Content="{Binding Status}"Click="btnTakeIt_Click"  Content="Take it" Margin="0,0,20,5" DockPanel.Dock="Right" FontSize="12" BorderThickness="1.5" HorizontalAlignment="Left"  VerticalAlignment="Bottom"  HorizontalContentAlignment="Center" VerticalContentAlignment="Center"  Foreground="#83D744"  Background="Transparent"  BorderBrush="#83D744" Width="130"   Height="40">
                                         <Button.Template>
                                            <ControlTemplate TargetType="Button">
                                            <Border BorderThickness="{TemplateBinding BorderThickness}"
                                                    BorderBrush="{TemplateBinding BorderBrush}"
                                                    Background="{TemplateBinding Background}">
                                                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                                            </Border>
                                            </ControlTemplate>
                                         </Button.Template>
                                    </Button>

code behind:后面的代码:

 public static List<LocalOrders> localOrders()
    {
        var results = DataServices.POS.proc_GetAllOrders().ToList();


        List<LocalOrders> localOrdersList = new List<LocalOrders>();

        foreach (var item in results)
        {
            LocalOrders lokal = new LocalOrders();
            if (item.IsInProgress)
            {
                localo.Pihvacena = true;
                localo.Status = "IN PROCESS";
            }
            else
            {
                lokalne.Status = "IT IS NOT YET IN PROCESS";
            }


            lokal.User = item.User;
            lokal.Quantity = Convert.ToInt32(item.Quantity);
            lokal.Title = item.Title;
            lokal.NumberOfOrder = item.NumberOfOrder;
            localOrdersList.Add(lokal);
        }
        return localOrdersList;
    }

So I can programaticaly check for status of order and set content of button like that.. is it good solution maybe?所以我可以以编程方式检查订单状态并像这样设置按钮的内容..这可能是一个好的解决方案吗?

Please refer below code.请参考以下代码。 I tried to make it work.我试图让它发挥作用。 Hope this works for you as well希望这也适用于你

 <DataGrid  HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden"  BorderBrush="#83D744" IsSynchronizedWithCurrentItem="False" VerticalGridLinesBrush="Transparent" Grid.Column="0"   RowHeaderWidth="0" CanUserAddRows="False" AutoGenerateColumns="False"  x:Name="datagrid1" Margin="10,150,8,50" Background="Transparent" RowBackground="#FF494949"  VerticalContentAlignment="Center" HorizontalContentAlignment="Center" ItemsSource="{Binding}">
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridColumnHeader}">
                <Setter Property="Background" Value="#83D744"/>
                <Setter Property="Opacity" Value="1"/>
                <Setter Property="Foreground" Value="White"/>
                <Setter Property="HorizontalContentAlignment" Value="Center" />
                <Setter Property="FontSize" Value="18"/>
                <Setter Property="FontFamily" Value="Arial"/>
                <Setter Property="Height" Value="50"/>
            </Style>


            <Style x:Key="TextInCellCenter" TargetType="{x:Type TextBlock}" >
                <Setter Property="TextAlignment" Value="Center"/>
            </Style>
            <Style TargetType="{x:Type TextBlock}" x:Key="RightAligElementStyle">
                <Setter Property="TextAlignment" Value="Right"/>
            </Style>
            <Style TargetType="{x:Type TextBlock}" x:Key="LeftAligElementStyle">
                <Setter Property="TextAlignment" Value="Left"/>
            </Style>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
       Color="Transparent"/>
        </DataGrid.Resources>


        <DataGrid.Columns >
            <DataGridTextColumn Binding="{Binding ProductName}"     ElementStyle="{StaticResource LeftAligElementStyle}"     Header="NAZIV ARTIKLA" MinWidth="350"    Foreground="White" FontSize="20" FontFamily="Verdana" />
            <DataGridTextColumn Binding="{Binding Quantity}"        ElementStyle="{StaticResource TextInCellCenter}"         Header="KOLIČINA"   MinWidth="200" Foreground="White"      FontSize="20" FontFamily="Verdana" />
        </DataGrid.Columns>

        <DataGrid.GroupStyle>
            <!-- Style for groups at top level. -->
            <GroupStyle>
                <GroupStyle.Panel>
                    <ItemsPanelTemplate>
                        <DataGridRowsPresenter/>
                    </ItemsPanelTemplate>
                </GroupStyle.Panel>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type GroupItem}">
                                    <Expander IsExpanded="True"  Background="Black" Opacity="0.7">
                                        <Expander.Header >
                                            <DockPanel Height="50" Margin="0,0,0,0"  Name="dockPanel" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=ActualWidth}">

                                                <Button Name="btnFinishOrder" DataContext="{Binding Items[0]}" Content="{Binding ButtonCaption}" Margin="0,0,55,5" DockPanel.Dock="Right" Click="BtnFinishOrder_OnClick" FontSize="12" BorderThickness="1.5" HorizontalAlignment="Left"  VerticalAlignment="Bottom"  HorizontalContentAlignment="Center" VerticalContentAlignment="Center"  Foreground="#83D744"  Background="Transparent"  BorderBrush="#83D744" Width="130"   Height="40">
                                                    <Button.Template>
                                                        <ControlTemplate TargetType="Button">
                                                            <Border BorderThickness="{TemplateBinding BorderThickness}"
                                                    BorderBrush=    "{TemplateBinding BorderBrush}"
                                                    Background=     "{TemplateBinding Background}">
                                                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                                                            </Border>
                                                        </ControlTemplate>
                                                    </Button.Template>
                                                </Button>

                                                <Button Name="btnTakeIt" Click="BtnTakeIt_OnClick"  DataContext="{Binding Items[0]}" Content="{Binding ButtonCaption}" Margin="0,0,20,5" DockPanel.Dock="Right" FontSize="12" BorderThickness="1.5" HorizontalAlignment="Left"  VerticalAlignment="Bottom"  HorizontalContentAlignment="Center" VerticalContentAlignment="Center"  Foreground="#83D744"  Background="Transparent"  BorderBrush="#83D744" Width="130"   Height="40">
                                                    <Button.Template>
                                                        <ControlTemplate TargetType="Button">
                                                            <Border BorderThickness="{TemplateBinding BorderThickness}"
                                                    BorderBrush="{TemplateBinding BorderBrush}"
                                                    Background="{TemplateBinding Background}">
                                                                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                                                            </Border>
                                                        </ControlTemplate>
                                                    </Button.Template>
                                                </Button>
                                                <TextBlock FontWeight="Normal" FontFamily="Verdana" FontSize="20" Height="25" Foreground="#83D744" Text="{Binding Items[0].ProductName}" />

                                            </DockPanel>
                                        </Expander.Header>
                                        <Expander.Content>
                                            <ItemsPresenter />
                                        </Expander.Content>
                                    </Expander>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </GroupStyle.ContainerStyle>
            </GroupStyle>
        </DataGrid.GroupStyle>
        </DataGrid>

public partial class MainWindow : Window
{
    private ICollectionView view;
    private ObservableCollection<Product> ordersList;
    public MainWindow()
    {
        InitializeComponent();
        this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
        this.WindowState = WindowState.Maximized;

        ordersList = new ObservableCollection<Product>()
        {
            new Product()
            {
                ProductName = "Prodct",
                Quantity = 1,
                NumberOfOrder = 100,
                IsInProgress = true,
                ButtonCaption = "Take it"
            },
            new Product()
            {
                ProductName = "Prodct1",
                Quantity = 2,
                NumberOfOrder = 1000,
                ButtonCaption = "Take it"

            },
            new Product()
            {
                ProductName = "Prodct2",
                Quantity = 3,
                NumberOfOrder = 10000,
                ButtonCaption = "Take it"

            },
            new Product()
            {
                ProductName = "Prodct3",
                Quantity = 4,
                NumberOfOrder = 100000,
                ButtonCaption = "Take it"

            },
        };

        view = CollectionViewSource.GetDefaultView(ordersList);

        view.GroupDescriptions.Add(new PropertyGroupDescription("NumberOfOrder"));
        DataContext = view;

        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(20);
        timer.Tick += Timer_Tick; ;
        timer.Start();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        foreach (var item in ordersList)
        {
            if (item.IsInProgress)
            {
                item.ButtonCaption = "Order is Still in progress";
            }
        }
    }

    private void BtnFinishOrder_OnClick(object sender, RoutedEventArgs e)
    {
        throw new NotImplementedException();
    }

    private void BtnTakeIt_OnClick(object sender, RoutedEventArgs e)
    {
        Button b = sender as Button;

        Product prod = b.DataContext as Product;

        b.BorderBrush = null;
        prod.ButtonCaption = "Order is in progress";
        b.FontSize = 12;
    }
}

class Product:INotifyPropertyChanged
{
    private string productName;

    public string ProductName
    {
        get { return productName ; }
        set
        {
            productName = value ;
            OnPropertyChanged("ProductName");
        }
    }

    private int quantity;

    public int Quantity
    {
        get { return quantity; }
        set
        {
            quantity = value;
            OnPropertyChanged("Quantity");
        }
    }

    public int NumberOfOrder { get; set; }

    public bool IsInProgress { get; set; }

    private string buttonCaption;

    public string ButtonCaption
    {
        get { return buttonCaption; }
        set
        {
            buttonCaption = value;
            OnPropertyChanged("ButtonCaption");
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM