WPF - 将相同的样式设置为多个控件

时间:2016-01-19 07:23:19

标签: c# wpf resourcedictionary

是否可以将相同的样式设置为多个控件? 我尝试了以下方式。但第一个按钮样式未正确应用,第二个样式应用正常。

设计

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class LoginManagerTest {

private static final String TAG = LoginManagerTest.class.getCanonicalName();
private String usernameStr = "androidtest@gmail.com";
private String passwordStr = "********";
private LoginManager loginManager;

@Test
public void testLogin() throws Exception {
    ResponseHandlerListener<String> listener = new ResponseHandlerListener<String>() {
        @Override
        public void onReceive(AxonResponse<String> response) {
            System.out.println("Login success ======= " + response.getResponseObject());
            String loginSuccess = Constants.LOGIN_SUCCESS;
            assertEquals(TAG, loginSuccess, response.getResponseObject());
        }
    };

    Context context = Robolectric.getShadowApplication().getApplicationContext();
    loginManager = new LoginManager(context);
    loginManager.login(usernameStr, passwordStr, null, listener);

}

@Test
public void testCalculate() throws Exception {
    Context context = Robolectric.getShadowApplication().getApplicationContext();
    loginManager = new LoginManager(context);
    int num = 5;
    int sum = loginManager.calculate(num);
    System.out.println("sum = " + sum);
    assertEquals(10, sum);
}

资源:

<StackPanel Orientation="Horizontal">
    <TextBlock Foreground="White" Margin="0,0,5,0">1st Button</TextBlock>
    <Button Style="{StaticResource ViewButton}" />
    <TextBlock Foreground="White" Margin="25,0,5,0">2nd Button</TextBlock>
    <Button Style="{StaticResource ViewButton}" />
</StackPanel>

enter image description here

2 个答案:

答案 0 :(得分:7)

您将两个相同的内容设置为两个不同的控件。问题是Setter.Value中的StackPanel不能有两个Parent,因此将应用最后一次使用。您可以使用ContentTemplate使其工作:

<Style x:Key="ViewButton" TargetType="Button" BasedOn="{StaticResource ButtonStyle}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="/Images/View.png" Stretch="None" Width="24" Height="24" />
                    <TextBlock Margin="5,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold">View</TextBlock>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Padding" Value="2,0,10,0"/>
</Style>

答案 1 :(得分:0)

      ....       ....       ....

您必须在as按钮中提及TargetType。你需要按照我写的样式名称编写样式属性。

希望这对你有用..

感谢