Search code examples
c#wpfdatatemplate

change combobox selecteditem in datatemplate


hi how i can change my combobox in datatemplate? why i cant use my combobox name like this:

cmbBase.SelectedIndex = 2;

this is my Datatemplate

<ContentControl>
                                <ContentControl.ContentTemplate>
                                    <DataTemplate>
                                        <Grid>
                                            <ComboBox Name="cmbBase">
                                                <ComboBoxItem Content="اول"/>
                                                <ComboBoxItem Content="دوم"/>
                                                <ComboBoxItem Content="سوم"/>
                                                <ComboBoxItem Content="چهارم"/>
                                                <ComboBoxItem Content="پنجم"/>
                                                <ComboBoxItem Content="ششم"/>
                                            </ComboBox>
                                            <TextBlock x:Name="tb" Text=" انتخاب پایه " IsHitTestVisible="False" Visibility="Hidden"/>
                                        </Grid>
                                        <DataTemplate.Triggers>
                                            <Trigger SourceName="cmbBase" Property="SelectedItem" Value="{x:Null}">
                                                <Setter TargetName="tb" Property="Visibility" Value="Visible"/>
                                            </Trigger>
                                        </DataTemplate.Triggers>
                                    </DataTemplate>
                                </ContentControl.ContentTemplate>
                            </ContentControl>

Solution

  • As Andy suggested you need to look into MVVM. if you still want to get it from the code behind please see how to use FrameworkTemplate.FindName

    PS, if you are trying to place text above the combobox until user selects an item this is not the way to do it, try looking into how to do combobox with watermark you will find plenty of answers in this site .