开发者

rename control in wpf using c#

开发者 https://www.devze.com 2023-02-25 14:16 出处:网络
if I add control in Microsoft Blend 4 without set Name to this control and I want to set name 开发者_运维问答to it and use it in c# how ?

if I add control in Microsoft Blend 4 without set Name to this control and I want to set name 开发者_运维问答to it and use it in c# how ? example I added button using Blend in my layout but without give it a name I want to give it a name using c# without x:Name="" in xaml


In your place I would give LogicalTreeHelper.GetChildren (this) a chance. It returns a collection of children to Window (this is a handle to Window) Reference MSDN
From there you can try to find your control.

But I think it is easier to try to rewrite the control (or look for another component) so you can have names on the children. That was your problem from the start.

Hope it helps
Gorgen


First, why in the world would you want to do that?

If you do not set a name you have no easy way of accessing the control. However you can get access to the control via relationships to other controls or events that pass a reference, for example the loaded event.

e.g.

private void Menu_Loaded(object sender, RoutedEventArgs e)
{
    (sender as Menu).Name = "MainMenu";
}

Or if the control is the child of another control:

(ControlStack.Children[0] as Menu).Name = "MainMenu";

But i cannot think of anything useful that could be achieved by that...

You probably just want to get a reference to the object which you can easily store in a class member. In some cases you can also slice up your XAML using resources.

e.g.

<local:SomethingIWouldLikeToReference x:Key="SomethingIWouldLikeToReference"/>
<local:UserControl x:Name="userControl">
    <Stuff>
        <MoreStuff Content="{StaticResource SomethingIWouldLikeToReference}"/>
    </Stuff>
</local:UserControl>
public MainWindow()
{
    InitializeComponent();
    MyReference = FindResource("SomethingIWouldLikeToReference") as SomethingIWouldLikeToReference;
}


Example if I have ListView Control and I want to use it to add items and remove items Make private ListView and initialize it

ListView temp_control_List = new ListView()

then make loaded Eventhandler from Blend so it will be in VS then

private void ListView_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            temp_control_List = sender as ListView;
        }

Now you can add and remove to and from the list view control from temp_control_List

0

精彩评论

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